HTML画布”;源顶”;以仅绘制先前绘制的形状

HTML Canvas "source-atop" to draw only the previously drawn shape

本文关键字:绘制 画布 源顶 HTML      更新时间:2023-09-26

我不知道如何让画布"source top"只在之前绘制的形状内绘制后续图形,而不是"所有"之前的形状。就像这个代码。它画一个"阴影"矩形,然后画一个矩形作为"对象",然后源在顶部,然后我想把下一个画的矩形夹在以前画的矩形("对象")里面,但它却夹在"阴影"里面。谢谢

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
}

source over是默认的comp操作,它总是在现有像素之上绘制像素。您需要使用source-atopdestination-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>