I’m trying to draw a rectangle at the mouse’s coordinates however I haven’t been able to get it to clear without clearing the other objects.
<!DOCTYPE html>
<html>
<style>
html, body {
height: 100%;
margin: 0;
}
body {
display: flex;
align-items: center;
justify-content: center;
}
canvas {
border: 1px solid orange;
background: black;
}
</style>
<head>
<base target="_top">
</head>
<body>
<canvas width="1250" height="600" id="game">
<script>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
let mouseX = 0;
let mouseY = 0;
function loop(){
ctx.clearRect(0,0,canvas.width,canvas.height);
let levelMax = 5;
let box = [];
for (j=0;j<levelMax;j++){
for (i=0;i<levelMax;i++){
ctx.fillStyle = "lime";
box.push({
X : (75 * i),
Y : 525 - (j*75),
Width : 75,
Height : 75
});
ctx.fillRect(box[(j*levelMax)+i].X, box[((j*levelMax)+i)].Y, box[i].Width, box[i].Height);
}
}
window.addEventListener("mousemove", (e)=>{
let posX = e.offsetX;
let posY = e.offsetY;
ctx.fillRect(posX, posY, 50, 50);
});
}
requestAnimationFrame(loop);
</script></canvas>
</body>
</html>
I tried to use ctx.clearRect(0, 0, canvas.width, canvas.height);
which didn’t clear the mouse’s squares or cleared the other squares but cleared old squares from the mouse as desired. I also tried to use ‘ctx.clearRect(e.offsetX, e.offsetY, 50, 50);’ which never really worked, either clearing the squares before they showed up and clearing the larger boxes if the mouse went over them, or just never cleared the mouse’s box.