如何使用JS为画布制作动画

时间:2019-03-06 04:14:22

标签: javascript html canvas

我正在尝试使用html canvas制作动画,但是我不知道我是否有最好的方法。

我正在尝试制作一个<canvas id="canvas"></canvas>并使用fillRect()在其上绘制一个矩形。

然后我要执行的函数onload的超时时间为500毫秒。

该函数基本上是通过更改矩形的x或y将矩形1px绘制到我想要的位置,然后用clearRect()将矩形绘制在起点上并跟随另一个一个。

我这样做正确吗?还是有更好的方法来解决这个问题?

2 个答案:

答案 0 :(得分:1)

如果必须多次使用此样式,建议您深入使用AnimeJS,这是一个JS库,可简化动画制作。 ^^

AnimeJS

它也支持延迟和时间表,这似乎就是您现在正在使用的^^

答案 1 :(得分:1)

您可以使用此结构

const canvas = document.getElementById('can');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.backgroundColor = 'white';

var someconstructorName = function(paramA,paramB,...){
    "Initialisation of variables and other things"   

    this.draw = function(){
        "your logic"
    }

    this.update = function(){
        "your update logic"
        this.draw();
    }
}

function animate(){
    requestAnimationFrame(animate)

}
animate();

在这里查看此笔会给您一个好主意: https://codepen.io/khanChacha/pen/YgpBxM

相关问题