我有一个svg的温度计来显示温度水平。温度计应使用提供的值更新值。为了显示温度计的值,针应该在顶部或底部移动。当我使用草图时,我看到针位置是通过高度和y轴控制的,但我在代码中没有看到这样。当使用javascript动画时,我如何设置svg的动画?
我附上了svg来搞清楚 http://svgshare.com/s/1C9
根据代码
,这是指针的一部分<path d="M84.9986191,1309.78732 C72.406414,1313.07575 63.2874461,1323.22544 63.2874461,1335.30443 L63.2874461,1423.54578 C63.2874461,1438.30467 76.922373,1450.19253 93.8469462,1450.19253 C110.771519,1450.19253 124.379137,1438.30467 124.379137,1423.54578 L124.379137,1335.30443 C124.379137,1323.22544 115.260169,1313.07575 102.667964,1309.78732 L102.667964,844.512322 L84.9986191,844.512322 L84.9986191,1309.78732 Z" id="needle" stroke="#000000" strokeWidth="2.13166976" fill="#FF0000"></path>
更新
我想移动矩形而不是行https://jsfiddle.net/8nLp81n0/
答案 0 :(得分:1)
这有助于您理解我之前的建议吗?
var mercury = document.getElementById("mercury");
var slider = document.getElementById("slider");
var yFor0 = 358;
var yFor100 = 50;
slider.addEventListener("input", function(evt) {
var sliderValue = evt.target.value;
displayTemperature(sliderValue);
});
function displayTemperature(temp)
{
var mercuryY = yFor0 + (temp * (yFor100 - yFor0)) / 100;
mercury.setAttribute("y1", mercuryY);
}
&#13;
svg {
float: left;
}
&#13;
<svg width="100" height="500">
<line id="mercury" x1="40" y1="50" x2="40" y2="500" stroke="red" stroke-width="20"/>
<rect x="30" y="30" width="20" height="469" fill="none" stroke="black" stroke-width="2"/>
<text x="60" y="55">100</text>
<text x="60" y="363">0</text>
<text x="60" y="455">-30</text>
</svg>
<input id="slider" type="range" min="-30" max="100" step="1" value="100"/>
&#13;
更新 - 矩形
Y坐标代表矩形的顶部,因此height
从那里下降。由于您希望矩形从底部向上增长,因此您需要同时更新y
和height
属性才能获得正确的结果。
document.querySelector('.ranger').addEventListener('input', function(event){
const rectNeedle = document.getElementById('Rectangle-2');
rectNeedle.setAttribute('y', 206 - event.target.value)
rectNeedle.setAttribute('height', event.target.value)
})
&#13;
<body>
<input type="range" min="1" max="100" step="1" class="ranger">
<p id="range-value"></p>
<svg width="53px" height="207px" viewBox="0 0 53 207" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
<!-- Generator: Sketch 3.3.3 (12081) - http://www.bohemiancoding.com/sketch -->
<title>moveLine</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">
<rect id="Rectangle-1" stroke="#979797" fill="#D8D8D8" sketch:type="MSShapeGroup" x="1" y="1" width="51" height="205"></rect>
<rect id="Rectangle-2" stroke="#979797" fill="#05243F" sketch:type="MSShapeGroup" x="1" y="163" width="51" height="43"/>
</g>
</svg>
</body>
&#13;