gpt4 book ai didi

javascript - Canvas 动画不断重绘前几帧

转载 作者:行者123 更新时间:2023-11-30 15:33:22 24 4
gpt4 key购买 nike

我现在花了大量的时间来解决这个问题,但我没有找到关于这个错误的任何说明。我开始用 JavaScript 构建一个简单的 HTML Canvas 动画。现在我希望小方 block 移动。这是代码(我也在使用 babeljs):

class Pod {
constructor(x,y) {
this.posX = x;
this.posY = y;
this.velX = getRandomNumber(-5,5);
this.velY = getRandomNumber(-5,5);
}

getPos() {
return ([this.posX,this.posY]);
}

move() {
this.posX += this.velX;
this.posY += this.velY;
}

render() {
ctx.save();
ctx.rect(this.posX,this.posY,3,3);
ctx.fillStyle = "#ffffff";
ctx.fill();
ctx.restore();
}
}
/*the classes end here*/

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

var elementsNum = 10;

const stack = new Array(elementsNum);

for(var i = 0; i < elementsNum; i++) {
stack[i] = new Pod(getRandomNumber(0,500),getRandomNumber(0,500));
}


function run() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#000000";
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx = canvas.getContext('2d');
for(var i = 0; i < elementsNum; i++) {
stack[i].move();
stack[i].render();
}
//window.requestAnimationFrame(run);
}


/*helper functions*/
function getRandomNumber(min, max) {
return Math.random() * (max - min) + min;
}

在函数 run() 运行一个循环后,小方 block (我称它们为 Pod)被渲染。下一个循环从使用 ctx.clearRect... 清除 Canvas 开始我正在重置上下文并开始移动,然后从堆栈中绘制 Pod。当我绘制第一个 Pod 时,它会绘制所有的 Pod 以及前一帧。

这是这个特定脚本的代码笔:http://codepen.io/erikputz/pen/YNNXqX

(我故意注释了requestAnimationFrame,所以你需要使用控制台调用run()函数)

感谢转发的帮助。

最佳答案

http://codepen.io/zfrisch/pen/bgazyO

这应该可以解决您的问题:

render() {    

ctx.beginPath();
ctx.rect(this.posX,this.posY,3,3);
ctx.fillStyle = "#ffffff";
ctx.fill();
ctx.closePath();

}

对于 Canvas ,您需要使用 beginPathclosePath 方法通过代码识别各个形状。在某些方法中,这是与生俱来的,例如在 fillRect 中。因此,上面的代码可以进一步简化为:

render() {    
ctx.fillStyle = "#ffffff";
ctx.fillRect(this.posX,this.posY,3,3);
}

当您只是声明一个形状 (rect) 时,您需要指定路径何时开始以及何时关闭,否则很可能会导致问题,例如您在你的原始代码。

此外,作为提示,除非您正在平移/缩放/旋转/或在 Canvas 元素上移动。填充形状不适用。

关于javascript - Canvas 动画不断重绘前几帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41946512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com