How can I clean the canvas without actually clearing everything I have drawn.Probably there is something wrong with the design of this program.I simply want to make the rectangle fall(I’ll fully animate it later) without clearing the rectangles drawn with the mouse.I tried to use c.clearRect(player.x, player.y, player.width, player.height) but it doesn’t work (and I don’t know why).
var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// class drawn rectangles
class Rectangle{
constructor(x,y,width,height,is_solid){
this.x = x;
this.y= y;
this.width=width;
this.height = height;
this.is_solid = false;
}
draw(x,y){
c.fillStyle = "red";
c.fillRect(x, y, 30, 30);
this.is_solid = true;
tiles_array.push(this);
}
}
// tiles array and tile object
let tiles_array = [];
let tile = new Rectangle();
//mouse object
var mouse = {
key_move: window.addEventListener('mousemove',(event)=>{
mouse.x = event.clientX;
mouse.y= event.clientY;
}),
key_click: canvas.addEventListener('click',()=>{
tile.draw(mouse.x, mouse.y);
})
}
class Player{
constructor(x,y,width,height,collision){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.collision = collision;
}
draw(){
c.fillStyle = "green";
c.fillRect(this.x, this.y, this.width, this.height);
}
}
let player = new Player(200,50,20,40,false);
// main function
function main(){
mouse.key_move;
mouse.key_click;
player.y += 10;
// first clear canvas then draw
player.draw();
requestAnimationFrame(main);
}
requestAnimationFrame(main);