我所要求的可能非常简单,但我在获得预期结果方面遇到了相当大的困难。
我想要一个形状(在本例中是正方形,但应该与其他形状(例如圆形等)一起使用)在离开另一个形状的边界时将其自身切断。
基本上,上图是我想要的,下图是我目前拥有的: /image/vxSLj.jpg
我听说这可以通过 globalCompositeOperation 来完成,但我正在寻找任何能够提供所需结果的解决方案。
这是当前代码,如果您无法使用 JSFiddle:
// Fill the background
ctx.fillStyle = '#0A2E36';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Fill the parent rect
ctx.fillStyle = '#CCA43B';
ctx.fillRect(100, 100, 150, 150);
// Fill the child rect
ctx.fillStyle = 'red';
ctx.fillRect(200, 200, 70, 70);
// And fill a rect that should not be affected
ctx.fillStyle = 'green';
ctx.fillRect(80, 80, 50, 50);
最佳答案
由于您需要对象之间的某种关系(场景图),因此您应该立即构建它。
从你的问题来看,似乎任何子元素都应该被其父元素剪切。
(是的,复合操作可以解决这个问题,但只有当在清晰的背景上绘制两个图形时,它们才很方便,否则事情会很快变得复杂,并且您可能必须使用背面 Canvas ,因此在这里剪切更简单。)
我在下面做了一个处理矩形情况的最基本的类,你会发现它并不是很难构建。
“场景”由背景矩形组成,它有两个子矩形,黄色和绿色。黄色矩形有一个红色 child 。
var canvas = document.getElementById('cv');
var ctx = canvas.getContext('2d');
function Rect(fill, x, y, w, h) {
var childs = [];
this.draw = function () {
ctx.save();
ctx.beginPath();
ctx.fillStyle = fill;
ctx.rect(x, y, w, h);
ctx.fill();
ctx.clip();
for (var i = 0; i < childs.length; i++) {
childs[i].draw();
}
ctx.restore();
}
this.addChild = function (child) {
childs.push(child);
}
this.setPos = function (nx, ny) {
x = nx;
y = ny;
}
}
// background
var bgRect = new Rect('#0A2E36', 0, 0, canvas.width, canvas.height);
// One parent rect
var parentRect = new Rect('#CCA43B', 100, 100, 150, 150);
// child rect
var childRect = new Rect('red', 200, 200, 70, 70);
parentRect.addChild(childRect);
// Another top level rect
var otherRect = new Rect('green', 80, 80, 50, 50);
bgRect.addChild(parentRect);
bgRect.addChild(otherRect);
function drawScene() {
bgRect.draw();
drawTitle();
}
drawScene();
window.addEventListener('mousemove', function (e) {
var rect = canvas.getBoundingClientRect();
var x = (e.clientX - rect.left);
var y = (e.clientY - rect.top);
childRect.setPos(x, y);
drawScene();
});
function drawTitle() {
ctx.fillStyle = '#DDF';
ctx.font = '14px Futura';
ctx.fillText('Move the mouse around.', 20, 24);
}
<canvas id='cv' width=440 height=440></canvas>
关于JavaScript Canvas 超出范围时裁剪形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33326977/