繁体   English   中英

JavaScript画布裁剪形状超出范围时

[英]JavaScript canvas clipping shape when out of bounds

我所要求的可能非常简单,但要获得预期的结果却遇到了很多麻烦。

我想要一个形状(在本示例中为正方形,但应与其他形状(例如圆形等)一起使用)在离开另一个形状的边界时将其自身切掉。

基本上,顶部图像是我想要的,底部图像是我目前拥有的: http : //imgur.com/a/oQkzG

我听说可以使用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);

JSFiddle链接

由于需要在对象之间建立某种关系-场景图-因此,现在应该构建它。
从您的问题来看,似乎任何子元素都应被其父元素剪裁。
(是的,可以进行复合操作,但是仅当在清晰的背景上绘制2个图形时它们才方便使用,否则事情会很快变得复杂,并且您可能必须使用后画布,因此此处的剪切更加简单。)

我在处理rect情况的最基本的类下面进行了学习,您会发现构建起来并不是很困难。

“场景”由背景Rect组成,Rect有两个孩子,黄色和绿色。 黄色的Rect有一个红色的孩子。

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM