是否可以边移动边在 Canvas 上做动画效果? 我只需要在 Canvas 的位置之间进行动画移动,
如在 css3 中:-webkit-transition-duration: 1s
;
感谢任何帮助。
<html>
<head>
<style>
#myCanvas {
-webkit-transition-duration: 1s;
}
</style>
<title>JS Bin</title>
</head>
<body>
<canvas id="myCanvas" width="1280" height="600" style="border:1px solid #d3d3d3;color:red;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var w = document.getElementById("myCanvas");
timer = setInterval(function() {
var f = Math.floor(1+Math.random()*680);
var f2 = Math.floor(1+Math.random()*400);
console.log (f, f2);
ctx.fillStyle="#FF0000";
ctx.clearRect(0, 0, c.width, c.height);
ctx.fillRect(f, f2, 100, 50);
w.onclick = function() {
clearInterval(timer);
falling();
}
}, 300 //the seconds of interval movement)
function falling(){
ctx.clearRect(0,0,c.width,c.height);
ctx.fillRect(500,500,100,50)
}
</script>
</body>
</html>
最佳答案
当然。如果您只想计算从起点到终点沿直线的临时位置,那么您可以这样做:
// percentComplete is a number between 0.00 and 1.00
// representing the current progress of the animation from start to end
var x = startingX+(endingX-startingX)*percentComplete;
var y = startingY+(endingY-startingY)*percentComplete;
如果你想制作有天赋的动画,那么你可以使用 Robert Penner 的 easing functions以非线性方式制作动画。
要为动画添加固定持续时间,您可以根据以下公式计算完成百分比:
var percentComplete = elapsedTime / animationDuration;
关于javascript - 如何在移动时在 Canvas 上制作动画效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35887191/