我无法弄清楚如何获得画布" source-atop"仅在之前绘制的形状内绘制后续绘图,而不是"所有"以前的形状。喜欢这段代码。它画了一个"阴影"矩形,然后绘制一个矩形作为"对象",然后source-atop,然后我希望下一个绘制的矩形被剪切在之前绘制的矩形内("对象") ,而是它夹在"阴影"内。感谢。
HTML
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas id="theCanvas" width="500" height="300" style="border:1px solid #000000;"></canvas>
<script type="text/javascript" src="externalJS.js"></script>
</body>
</html>
JAVASCRIPT
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded () {
canvasApp();
}
function canvasApp() {
var canvas = document.getElementById('theCanvas');
var context = canvas.getContext('2d');
context.fillStyle = '#999999';// this rectangle is supposed to be the "shadow"
context.fillRect(42, 42, 350, 150);
context.fillStyle = '#dddddd';// this rectangle is supposed to be on top..."
context.fillRect(35, 35, 350, 150);
context.globalCompositeOperation="source-atop";
context.fillStyle = '#00ff00';
context.fillRect(100, 100, 350, 150);//... and then this rectangle is supposed to be clipped inside the previously
drawn one... not the shadow one
}
答案 0 :(得分:0)
source over
是默认的comp操作,并且总是在存在的那些上绘制像素。您需要使用source-atop
和destination-over
。
同样在使用comp操作时,渲染顺序不再是前回。在这种情况下,最后绘制阴影。如果是先绘制它会干扰source-atop
操作。
以下是一种方法。但我建议您使用ctx.clip()
,因为此示例更适合ctx.clip()
,因为形状简单。仅在具有非常复杂的图像并且需要按像素控制裁剪的情况下使用comps。
var canvas = document.getElementById("canV");
var ctx = canvas.getContext("2d");
// draw a circle
function drawCircle(x,y){
ctx.beginPath();
ctx.arc(x,y,150,0,Math.PI*2);
ctx.fill();
}
ctx.clearRect(0,0,canvas.width,canvas.height); // ensure a clear canvas
ctx.globalCompositeOperation = "source-over"; // draw the cyan circle normaly
ctx.fillStyle = "#3AE";
drawCircle(200,200); // draw the main circle
ctx.globalCompositeOperation = "source-atop"; // draw the new pixels from source
// ontop of any existing pixels
// and not where the are no pixels
ctx.fillStyle = "#F70";
drawCircle(300,300); // draw the clipped circle;
ctx.globalCompositeOperation = "destination-over"; // draw the shadow.
// Where pixels in destination
// stay ontop.
ctx.fillStyle = "#888";
drawCircle(210,210); // draw the shadow;
#canV {
width:500px;
height:500px;
}
<canvas id = "canV" width=500 height=500></canvas>