使用纯javascript(没有Raphael或其他插件)对随着时间推移绘制的线进行动画处理[关闭]

问题描述 投票:0回答:2

我正在尝试显示正在绘制的线条的动画,在 SVG 元素内绘制一条线条。

类似的问题有指向 Raphael JS 库的答案。 然而,由于限制,我无法使用互联网上提供的任何库。

有关如何在 JS 中执行此操作的一些指示会很有帮助。

javascript animation line
2个回答
4
投票

我从来没有在生活中使用过 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>

参见:http://jsfiddle.net/YSmDH/


0
投票

您应该使用

<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上下文,然后创建新的,您可以为线条设置动画

是一个非常好的画布操作教程。

© www.soinside.com 2019 - 2024. All rights reserved.