HTML画布”;源顶”;以仅绘制先前绘制的形状
HTML Canvas "source-atop" to draw only the previously drawn shape
我不知道如何让画布"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-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>
相关文章:
- Javascript绘制画布内存泄漏
- 如何在重新绘制画布时防止形状的痕迹-Javascript
- 鼠标悬停时重新绘制画布
- 使用Javascript在HTML5中重新绘制画布
- 如何从数据库中动态绘制画布中的图像
- Javascript绘制画布
- 根据64字符串绘制画布图片时出错
- 您如何每 x 秒在另一个画布或图像上重新绘制画布
- 如何在正确的位置绘制画布元素
- 有没有一种好方法可以添加新框并使用 javascript 重新绘制画布
- flot:无法绘制画布内包含标签的饼图
- 可绘制画布在错误的位置渲染线条
- 如何使用延迟的 for 循环绘制画布
- 在html表中绘制画布;不能在JavaScript中工作
- 在没有闪烁的情况下重新绘制画布html5
- 单击按钮即可更新/重新绘制画布
- JS/HTML5-用数组中的图像数据重新绘制画布
- 可以'不要在移动浏览器上用手指绘制画布
- Kinetics.js可以根据用户操作自动重新绘制画布
- 使用视频循环绘制画布