Answer the question
In order to leave comments, you need to log in
Why is the Canvas not cleared when using clearRect?
There are two functions, one draws a red square, the other a green one. At the start, a function with a red square is launched, by clicking on it, the second function is launched and canvas cleaning is called. In theory, the red square should disappear and the green one should be drawn, and when you click on the green one, it will be overwritten and red will be called. But two squares are drawn - why? How to make the canvas completely clear from the first function to a white screen and start the second function and vice versa?
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="canvas" width = 1000 height = 620 style = "border: 1px solid #000000;"></canvas>
</body>
</html>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let clearCanvas = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
};
let launchLayerOne = function() {
canvas.style.background = 'black';
ctx.rect(50, 50, 100, 100);
ctx.fillStyle = 'rgba(247, 7, 7, 0.8)';
ctx.fill()
canvas.onmousedown = function(e) {
let rect = this.getBoundingClientRect();
x = e.clientX - rect.left;
y = e.clientY - rect.top;
let detect
ctx.isPointInPath(x, y) ? detect = 1 : detect = 0;
if(detect === 1) {
clearCanvas();
launchLayerTwo();
}
};
};
launchLayerOne()
let launchLayerTwo = function() {
canvas.style.background = 'grey';
ctx.rect(250, 50, 100, 100);
ctx.fillStyle = 'rgba(13, 171, 10, 0.8)';
ctx.fill()
canvas.onmousedown = function(e) {
let rect = this.getBoundingClientRect();
x = e.clientX - rect.left;
y = e.clientY - rect.top;
let detect
ctx.isPointInPath(x, y) ? detect = 1 : detect = 0;
if(detect === 1) {
clearCanvas();
launchLayerOne();
}
};
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question