簡體   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