我想画一幅图像,擦掉一些零件,然后再画上面。有点像:
ctx.drawImage(favicon, 0, 0);
ctx.fillStyle = 'transparent';
ctx.fillRect(10, 0, 6, 6);
ctx.fillStyle = 'red';
ctx.fillRect(12, 0, 4, 4);
如何删除部分图像?
答案 0 :(得分:4)
.clearRect
是一个不错的选择,如您对问题的评论中所示。
如果你有非矩形区域(或只是一组像素)来透明,那么你也可以使用destination-out
合成来使这些像素透明。
此示例从JellyBeans图像开始,并从中剪切出太阳图像:
<强>软糖强>
太阳(用作不规则形状的橡皮擦)
晒太阳的豆形软糖已被抹去
带注释的示例代码:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var jellybeans=new Image();
jellybeans.onload=start;
jellybeans.src="https://dl.dropboxusercontent.com/u/139992952/multple/jellybeans.jpg";
var sun=new Image();
sun.onload=start;
sun.src='https://dl.dropboxusercontent.com/u/139992952/multple/sun.png';
var imageCount=2;
function start(){
// wait for all images to load
if(--imageCount>0){return;}
// resize the canvas to jellybean size
canvas.width=jellybeans.width;
canvas.height=jellybeans.height;
// draw the jellybeans on the canvas
ctx.drawImage(jellybeans,0,0);
// Set compositing to "destination-out"
// All new drawings will act to erase existing pixels
ctx.globalCompositeOperation='destination-out';
// Draw the sun image
// Drawing will erase the sun image shape from the jellybeans
// You could also erase with any drawing commands (lines,arcs,curves,etc)
ctx.drawImage(sun,100,50);
// always clean up!
// Reset compositing to default mode
ctx.globalCompositeOperation='source-over';
}
#canvas{border:1px solid red; margin:0 auto; }
<h4>Jellybeans with sun-shaped erased</h4>
<canvas id="canvas" width=300 height=300></canvas>