简体   繁体   English

如何清除矩形边框? (JS,Canvas)

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

I'm trying to clear only the strokeRect() and keep content in that rectangle. 我试图只清除strokeRect()并将内容保留在该矩形中。 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! 无法弄清楚如何..提前感谢!

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> 

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: 所以要做一个简单的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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM