首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HTML画布"source-atop“仅绘制先前绘制的形状

HTML画布"source-atop“仅绘制先前绘制的形状
EN

Stack Overflow用户
提问于 2015-11-22 11:21:03
回答 1查看 873关注 0票数 0

我不知道如何让画布“source- to”只在之前绘制的形状内绘制后续的图形,而不是“所有”先前的形状。就像这段代码。它绘制一个“阴影”矩形,然后绘制一个矩形作为“对象”,然后在源代码顶部,然后我希望下一个绘制的矩形被裁剪到先前绘制的矩形(“对象”)中,但它却裁剪在“阴影”中。谢谢。

HTML

代码语言:javascript
复制
<!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

代码语言: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
}
EN

回答 1

Stack Overflow用户

发布于 2015-11-23 03:49:50

source over是默认的复合操作,并且始终在现有像素上绘制像素。您需要使用source-atopdestination-over

此外,当使用comp操作时,渲染顺序不再是从后到前。在这种情况下,最后绘制阴影。如果它首先被绘制,它将干扰source-atop操作。

下面是一种方法。但我建议您使用ctx.clip(),因为这个示例更适合ctx.clip(),因为它的形状很简单。仅在具有非常复杂的图像并且需要每像素控制裁剪的情况下才使用comps。

代码语言:javascript
复制
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;
代码语言:javascript
复制
#canV {
  width:500px;
  height:500px;
}
代码语言:javascript
复制
<canvas id = "canV" width=500 height=500></canvas>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33851260

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档