我不知道如何让画布“source- to”只在之前绘制的形状内绘制后续的图形,而不是“所有”先前的形状。就像这段代码。它绘制一个“阴影”矩形,然后绘制一个矩形作为“对象”,然后在源代码顶部,然后我希望下一个绘制的矩形被裁剪到先前绘制的矩形(“对象”)中,但它却裁剪在“阴影”中。谢谢。
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
}发布于 2015-11-23 03:49:50
source over是默认的复合操作,并且始终在现有像素上绘制像素。您需要使用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>
https://stackoverflow.com/questions/33851260
复制相似问题