使用javascript绘制动画线(没有Raphael或其他插件)

Drawing an animated line using javascript (without Raphael or other plugins)

本文关键字:Raphael 其他 插件 没有 javascript 绘制 动画 使用      更新时间:2023-09-26

我正在尝试在SVG元素内绘制动画线。这条线是在一段时间内绘制的。

我搜索过,但是所有的答案通常都指向拉斐尔图书馆。但是,我不能使用互联网上提供的任何库。

需要一些指示从哪里开始

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

您应该使用<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-Context,然后创建新的,你可以动画你的行

这是一个非常好的关于画布操作的教程