Gustavo Passos
Gustavo Passos

Reputation: 43

How do I clear ONLY rectangle borders? (JS , Canvas)

I'm trying to clear only the strokeRect() and keep content in that rectangle. In this example, how do I clear green rectangle without affecting the red one?

 var cut = [50, 70, 100, 100]
 var cut1 = [60, 85, 60, 60]
 var c = document.getElementById("canvas");
 var ctx = c.getContext("2d");
 ctx.beginPath();
 ctx.rect(cut[0], cut[1], cut[2], cut[3]);
 ctx.lineWidth = 3;
 ctx.strokeStyle = 'green';
 ctx.stroke();
 ctx.closePath();
 
 ctx.beginPath();
 ctx.rect(cut1[0], cut1[1], cut1[2], cut1[3]);
 ctx.lineWidth = 3;
 ctx.strokeStyle = 'red';
 ctx.stroke();
 ctx.closePath();
<canvas id="canvas" width=400px height=200px></canvas>

Can't figure out how.. Thanks in advance!

Upvotes: 1

Views: 1839

Answers (2)

Kaiido
Kaiido

Reputation: 136638

In your case, clear & redraw is what you really need, but just for completeness, to clear in any shape, you can use compositing operations.

By setting the compositing mode to destination-out, all the pixels that should normally have been filled by your drawings will actually get rendered as transparent.

So to make a simple clear-stroke-rect:

var ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(20, 20, 80, 80);

// clear
ctx.globalCompositeOperation = 'destination-out';
ctx.lineWidth = 5;
ctx.strokeRect(40,40,30,30);

// set back to 'normal'
ctx.globalCompositeOperation = 'source-over';
<canvas id="canvas"></canvas>

But using compositing, you can really clear in any shape, even from bitmap with transparency:

var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
  ctx.fillStyle = 'red';
  ctx.fillRect(20, 20, 80, 80);

  // clear
  ctx.globalCompositeOperation = 'destination-out';
  ctx.drawImage(img, 40,40);
  
  // set back to 'normal'
  ctx.globalCompositeOperation = 'source-over';
};
img.src = 'https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png';
<canvas id="canvas"></canvas>

Upvotes: 0

enxaneta
enxaneta

Reputation: 33034

You need to clear the canvas and draw the red rectangle again.

var c = document.getElementById("canvas");
 c.width=400;
 c.height=200;
 var ctx = c.getContext("2d");

 var cut = [50, 70, 100, 100]
 var cut1 = [60, 85, 60, 60]
 
 function drawRectangle(cut,fill){
 ctx.beginPath();
 ctx.rect(cut[0], cut[1], cut[2], cut[3]);
 ctx.lineWidth = 3;
 ctx.strokeStyle = fill;
 ctx.stroke();
 ctx.closePath();
 }

drawRectangle(cut,"green");
drawRectangle(cut1,"red");



clear.addEventListener("click",()=>{
ctx.clearRect(0,0, c.width, c.height);
drawRectangle(cut1,"red");
});
canvas{display:block;}
<button id="clear">clear</button>
<canvas id="canvas" width=400px height=200px></canvas>

Upvotes: 3

Related Questions