首页 > 解决方案 > 如何用js动画画布

问题描述

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

我正在尝试<canvas id="canvas"></canvas>使用fillRect().

然后我正在执行一个函数 onload,它的超时时间为 500 毫秒。

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

我这样做对吗?还是有更好的方法来解决它?

标签: javascripthtmlcanvas

解决方案


你可以使用这个结构

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();

在这里查看这支 Pen,它会给你一个好主意: https ://codepen.io/khanChacha/pen/YgpBxM


推荐阅读