const ctxB = background.getContext("2d");
const ctxF = foreground.getContext("2d");
ctxB.textAlign = "center";
ctxB.textBaseline = "middle";
ctxB.font ="20px arial";
ctxB.fillText("Some Background text",150,25);
ctxB.fillText("Some Background text",150,75);
ctxB.fillText("Some Background text",150,125);
ctxF.lineJoin = "round";
ctxF.fillStyle = "red";
ctxF.fillRect(0,0,300,150);
ctxF.lineWidth = 8;
ctxF.globalCompositeOperation = "destination-out";
ctxF.strokeRect(25,25,250,100);
ctxF.fillRect(75,50,150,50);
ctxF.globalAlpha = 0.5;
ctxF.fillRect(65,40,170,70);
ctxF.globalCompositeOperation = "source-over";
canvas {
position : absolute;
top : 0px;
left: 0px;
}
<canvas id = "background"></canvas>
<canvas id = "foreground"></canvas>
注:RGBA - >(紅,藍,綠,阿爾法),α值(範圍從[0,1])控制不透明度,1,爲完全不透明[W3 CSS3顏色](https://www.w3schools.com/css/css3_colors.asp) –
使用clearRect清除現有的矩形 – karthick
我不認爲[this](https://jsfiddle.net/2gLj52u4/)會工作。 :P儘管如此,我認爲這是不可能的。你可能會有更好的運氣記錄「繪畫」過程並重播它,但不包括紅色輪廓步驟。帆布很像繪畫。你不能撤消那個中風。 –