我正在尝试显示正在绘制的线条的动画,在 SVG 元素内绘制一条线条。
类似的问题有指向 Raphael JS 库的答案。 然而,由于限制,我无法使用互联网上提供的任何库。
有关如何在 JS 中执行此操作的一些指示会很有帮助。
我从来没有在生活中使用过 SVG,但在快速谷歌后 10 分钟内我想出了:
<svg width=200 height=200>
<line id="myLine" x1="5" y1="10" x2="5" y2="10" stroke-width=".5" stroke="red"/>
</svg>
<script>
var line = document.getElementById('myLine');
var count = 0;
var interval = window.setInterval(function() {
line.setAttribute('y2', 2 + +line.getAttribute('y2'));
line.setAttribute('x2', 1 + +line.getAttribute('x2'));
if (count++ > 75)
window.clearInterval(interval);
}, 100);
</script>
您应该使用
<canvas id='mycanvas' width='300' height='300' />
元素并像这样画线:
function drawShape(){
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext){
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Stroked triangle
ctx.beginPath();
ctx.moveTo(125,125);
ctx.lineTo(125,45);
ctx.lineTo(45,125);
ctx.closePath();
ctx.stroke();
}
}
通过添加超时和清除您的2D上下文,然后创建新的,您可以为线条设置动画
这是一个非常好的画布操作教程。