Javascript画布动画(棒图运动)

时间:2018-03-05 20:51:38

标签: javascript html animation canvas

我一直在寻找一个地方来展示如何做动画。我已经看到你可以将积木移动到一个区域并向后移动,一个圆圈上下移动,但没有任何东西可以移动他的身体。我使用css动画,但想尝试javascript画布。这个数字有什么方法可以在Canvas上挥动动画吗?我假设需要setTimeout?

<canvas id="canvas" width="400px" height="400px" >
Your browser does not support HTML5 Canvas element
</canvas>

<script>
var canvas = document.getElementById("canvas");
context = canvas.getContext("2d"); // get Canvas Context object

context.beginPath();
context.fillStyle = "black"; // #000000
context.arc(200.width, 50, 30, 0, Math.PI * 2, true);
context.fill(); //fill the circle  

context.beginPath(); 
context.lineWidth = 6;
context.stroke();

//body
context.beginPath();
context.moveTo(200, 80);
context.lineTo(200, 180);
context.strokeStyle = "black";
context.stroke();

//arms
context.beginPath();
context.strokeStyle = "black";
context.moveTo(200, 100);
context.lineTo(150, 130);
context.moveTo(200, 100);
context.lineTo(250, 130);
context.stroke();

//legs
context.beginPath();
context.strokeStyle = "black";
context.moveTo(200, 180);
context.lineTo(150, 280);
context.moveTo(200, 180);
context.lineTo(250, 280);
context.stroke();
</script>     

1 个答案:

答案 0 :(得分:4)

首先,由于我们要反复绘制一个框架,我们需要将绘图代码放入draw function

Window对象上有一个名为requestAnimationFrame的方法,只要可用,它就会一直调用此draw函数。这可以防止窗口耗尽所有内存,如果在动画运行时翻转标签,则会暂停动画。过去曾使用setTimeoutsetInterval,但不要再使用它们。

由于所有发生的事情都是draw函数一直被调用,为了只定期更改图形,我们设置一个变量(在这种情况下称为wave),确定手臂的方式画。

timestamp用于确定自调用draw后最后一次绘制以来是否已经过900毫秒。如果它还没有继续调用该函数,直到该持续时间已经过去。通常情况下,我们希望这更快,但因为我们正在使用&#39; wave&#39;作为一个例子,我们只有两个绘图状态(向上或向下),它可以正常工作。

let timestamp = Date.now();
let wave = false;


draw();

&#13;
&#13;
var canvas = document.getElementById("canvas");
context = canvas.getContext("2d"); // get Canvas Context object
let timestamp = Date.now();
let wave = false;


draw();

function draw() {
if(Date.now() < (timestamp+900)) return requestAnimationFrame(draw);

context.clearRect(0, 0, window.innerWidth, window.innerHeight);
context.beginPath();
context.fillStyle = "black"; // #000000
context.arc(200, 50, 30, 0, Math.PI * 2, true);
context.fill(); //fill the circle  

context.beginPath(); 
context.lineWidth = 6;
context.stroke();

//body
context.beginPath();
context.moveTo(200, 80);
context.lineTo(200, 180);
context.strokeStyle = "black";
context.stroke();

//arms
context.beginPath();
context.strokeStyle = "black";
context.moveTo(200, 100);
context.lineTo(150, 130);
if(wave) { 
context.moveTo(200, 100);
context.lineTo(250, 130);
wave = false;
}
else {
context.moveTo(200, 100);
context.lineTo(250, 70);
wave = true;
}
context.stroke();

//legs
context.beginPath();
context.strokeStyle = "black";
context.moveTo(200, 180);
context.lineTo(150, 280);
context.moveTo(200, 180);
context.lineTo(250, 280);
context.stroke();
timestamp = Date.now();
requestAnimationFrame(draw);
}
&#13;
<canvas id="canvas" width="400px" height="400px" >
Your browser does not support HTML5 Canvas element
</canvas>
&#13;
&#13;
&#13;