I’m trying to move a block of butter down a canvas window. Here is the code sandbox: https://codesandbox.io/s/empty-sandbox-forked-tygc5z?file=/index.html
The important code is index.js:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.onresize = function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
const arr = ["butter", "bread", "cheese"];
const sprites = [];
const tilesheet = new Image();
const butter1 = {
img: tilesheet,
sourceWidth: 24,
sourceHeight: 60,
sourceX: 3,
sourceY: 2,
vy: 0,
timer: 0,
x: 0,
y: 0,
scale: 1,
visible: false
};
const butter2 = {
img: tilesheet,
sourceWidth: 33,
sourceHeight: 60,
sourceX: 27,
sourceY: 2,
vy: 0,
timer: 0,
x: 0,
y: 0,
scale: 1,
visible: false
};
const butter3 = {
img: tilesheet,
sourceWidth: 24,
sourceHeight: 60,
sourceX: 60,
sourceY: 2,
vy: 0,
timer: 0,
x: 60,
y: 0,
scale: 1,
visible: false
};
tilesheet.addEventListener(
"load",
() => {
arr.forEach((_, i) => {
const b1 = { ...butter1 };
b1.timer = i * 62;
sprites.push(b1);
const b2 = { ...butter2 };
b2.x = b1.x + b1.sourceWidth * b1.scale;
b2.timer = b1.timer;
sprites.push(b2);
const b3 = { ...butter3 };
b3.x = b2.x + b2.sourceWidth * b2.scale;
b3.timer = b2.timer;
sprites.push(b3);
});
render();
},
false
);
tilesheet.src = "./src/sample.png";
function render() {
requestAnimationFrame(render);
//console.log(arr.length, sprites.length);
sprites.forEach((sprite, i) => {
sprite.timer -= 0.3;
if (sprite.timer <= 0) {
sprite.visible = true;
}
if (sprite.visible) {
sprite.vy = 0.3;
sprite.y += sprite.vy;
}
});
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(229, 242, 24, 1)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
sprites.forEach((sprite) => {
if (sprite.visible) {
ctx.drawImage(
sprite.img,
sprite.sourceX,
sprite.sourceY,
sprite.sourceWidth,
sprite.sourceHeight,
sprite.x,
sprite.y,
sprite.sourceWidth * sprite.scale,
sprite.sourceHeight * sprite.scale
);
}
});
}
As you can see in the code sandbox, there is a weird line appearing when the blocks of butter go down the window:
It is not there when the speed is 1 instead of 0.3 or when the butter is not moving.
Is there anyway I can get rid of the weird line? Thanks