【问题标题】:Canvas, animate line to move up and down画布,动画线上下移动
【发布时间】:2017-04-28 17:22:47
【问题描述】:

我在HTML5 Canvas 中创建了一条水平线。我想为这条线设置动画以向上和向下移动无穷大。有可能吗?

function horizontal_line() {
  context.beginPath();
  context.moveTo(100, 100);
  context.lineTo(5000, 100);
  context.strokeStyle = "Green";
  context.stroke();
}

【问题讨论】:

  • 你能在这里发布你的问题的相关 HTML、CSS、JS 代码吗?
  • 请参阅 thisthis 示例以了解您的动画尝试。希望有帮助。 :)

标签: html canvas html5-canvas


【解决方案1】:

对于动画,您需要有一种方法来绘制不同的帧,并且在每一帧中您必须删除前一个,计算线条的新位置,然后重新绘制线条:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "Green";
var posY = 0;
var lineLength = 10;
var speed = 2;

function drawLine() {
	ctx.beginPath();
  ctx.moveTo(10, posY);
  ctx.lineTo(10, posY+lineLength);
  ctx.stroke();
}

function moveLine () {
	posY += speed;
  
  if (posY < 0 || posY > canvas.height) {
	  speed = speed * -1;
  }
}

function loop() {
	// clear old frame;
  ctx.clearRect(0,0,canvas.width, canvas.height);
  moveLine();
  drawLine();
  requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
&lt;canvas id="canvas"&gt;&lt;/canvas&gt;

在此示例中,requestAnimationFrame 为您提供所需的帧,因此函数loop() 被一遍又一遍地调用。在那里我们用clearRect()清除旧框架,计算新位置,然后用drawLine()绘制新线。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2023-03-08
    • 2020-05-25
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多