How do hide element/object in canvas?

2464 views javascript
4

I want to hide a second element and show first element when checked second checkbox and unchecked the first one.

But now when I use "c.clearRect(0, 0, canvas.width, canvas.height);", It's disappear both of elements.

var checkBox = document.getElementById("myCheck");
var checkBox2 = document.getElementById("myCheck2");
var text = document.getElementById("text");
if (myCheck.checked == true){
  c.fillRect(20, 20, 150, 100);
} else {
   c.clearRect(0, 0, canvas.width, canvas.height);
}

if (myCheck2.checked == true) {
  c.fillRect(500, 100, 100, 100);  //I want hide this element**strong text**
} else {
  c.clearRect(0, 0, canvas.width, canvas.height);
}

answered question

If you only want to erase one element only erase the area that that element takes up. Or always clear the whole canvas before doing any drawing

There are no "elements" on canvas. It's a canvas. The only way something disappears is if you paint something over it. clearRect is a misnomer - it actually paints a rectangle (or the shape set by path) with transparent black. If you paint over more than you wanted, you'll have to repaint the things you covered but didn't want to.

It's very helpful and thanks so much for your recommend.

1 Answer

1

You can call c.clearRect(); before drawing the boxes!

c.clearRect(0, 0, canvas.width, canvas.height);

var checkBox = document.getElementById("myCheck");
var checkBox2 = document.getElementById("myCheck2");
var text = document.getElementById("text");

if (checkBox.checked == true){
  c.fillRect(20, 20, 150, 100);
} else {
   c.clearRect(0, 0, canvas.width, canvas.height);
}

if (checkBox2.checked == true) {
  c.fillRect(500, 100, 100, 100);  //I want delete this element**strong text**
}

posted this

Have an answer?

JD

Please login first before posting an answer.