Javascript 提高Canvas-draw调用性能

Javascript 提高Canvas-draw调用性能,javascript,typescript,canvas,Javascript,Typescript,Canvas,我想画好几个点。我就是这么做的: let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); function render () { window.requestAnimationFrame(render); // clear screen ctx.clearRect(0, 0, cwidth, cheight); for (let p of partic

我想画好几个点。我就是这么做的:

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

function render () {
    window.requestAnimationFrame(render);
    // clear screen
    ctx.clearRect(0, 0, cwidth, cheight);
    for (let p of particles) {
        p.rmove();
        p.render(ctx);
    }
}

render();
my point的绘图函数如下所示:

class Point {

    x: number;
    y: number;

    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    rmove() {
        this.x += Math.round(Math.random() < 0.5 ? -1 : 1);
        this.y += Math.round(Math.random() < 0.5 ? -1 : 1);
    }

    render (ctx) {
        ctx.fillStyle = "gray";
        ctx.beginPath();
        ctx.rect(this.x, this.y, 1.5,1.5);
        ctx.fill();
        ctx.stroke();
    }
}
类点{
x:数字;
y:数字;
构造函数(x,y){
这个.x=x;
这个。y=y;
}
rmove(){
this.x+=Math.round(Math.random()<0.5?-1:1);
this.y+=Math.round(Math.random()<0.5?-1:1);
}
渲染(ctx){
ctx.fillStyle=“灰色”;
ctx.beginPath();
ctx.rect(this.x,this.y,1.5,1.5);
ctx.fill();
ctx.stroke();
}
}
请注意,我对
rmove()
函数中的值进行了舍入,因为canvas使用整数坐标更快地绘制点


我想以某种方式将所有这些绘图调用放在一起。

在给定上下文(甚至可以是Path2D)上进行点跟踪,并保留渲染器的实际绘图

在跟踪
rect
之前,您需要做的就是将上下文
移动到它们自己的坐标

类点{
构造函数(x,y){
这个.x=x;
这个。y=y;
}
rmove(){
this.x+=Math.round(Math.random()<0.5?-1:1);
this.y+=Math.round(Math.random()<0.5?-1:1);
}
跟踪(ctx){
ctx.moveTo(this.x,this.y);
ctx.rect(this.x,this.y,1.5,1.5);
}
}
const canvas=document.getElementById('canvas');
const ctx=canvas.getContext('2d');
常数cwidth=canvas.width=300;
const cheight=canvas.height=300;
常量粒子=Array.from(
{长度:5000},
()=>新点(cwidth/2,cheight/2)
);
函数设置动画(){
更新();
draw();
window.requestAnimationFrame(动画);
}
函数更新(){
for(设p为粒子数){
p、 rmove();
}
}
函数绘图(){
//清屏
ctx.clearRect(0,0,cwidth,cheight);
//定义我们的单一路径
ctx.beginPath();
for(设p为粒子数){
p、 微量元素(ctx);
}
ctx.fillStyle=“灰色”;
stroke();//OP将其反转,但填充颜色几乎不可见
//(1.5宽度-2*0.5笔划只留下0.5填充=>抗锯齿。。。
ctx.fill();
}
window.requestAnimationFrame(动画);

你可以使用webworkers:你能告诉我们更多关于代码示例的信息吗?在这种情况下,它真的是合理的吗?我本来希望从循环中提取一段beginpath代码,但结果不是那么简单。