2014-11-15 20 views
0

我已經用多個畫布(位置:絕對,不同的z-idexes)構建了一個橫幅但是......但我願意用ONE畫布重新創建整個事物並且它證明成爲一個問題。橫幅的動畫非常複雜,所以這裏有一個簡單的問題,它會幫助我理解它的工作原理。一個畫布,多個分層的內容

我想「砍」一桿進洞在黑色矩形所以紅色變爲可見

下面是代碼:

red.beginPath(); 
    red.fillStyle = '#af0000'; 
    red.fillRect(33, 33, 200, 60); // drawing red rectangle 
    red.closePath(); 

    red.beginPath(); 
    red.fillStyle = '#000'; 
    red.fillRect(77, 66, 120, 60); // drawing black one 
    red.clearRect(110, 80, 20, 20); // cutting 20X20 pixels rectangle 
    red.closePath(); 

我知道爲什麼兩個矩形受到影響。這只是爲了說明我想實現的目標。我可以用兩塊帆布做成 - 在一塊上繪製紅色矩形,在另一塊上繪製黑色矩形,然後切割黑色矩形 - 但我只想用一塊畫布繪製它。 另外 - 我知道我可以重新繪製紅色部分,但懷疑這是一個明智的解決方案。

這裏是小提琴: http://jsfiddle.net/hej11px9/

提前感謝!

我知道這是一個非常業餘的問題,但是...無論如何 - 試圖找到沒有運氣的解決方案。

回答

1

答案不是那麼容易:有孔畫畫,你必須夾您的矩形的一部分,當截割是指夾在
但有夾出一個矩形的解決方案:夾在整個畫布上,然後逆時針減去內部矩形。

我也有你的代碼'數據驅動',所以更容易做出改變。

http://jsfiddle.net/casemate/hej11px9/1/

enter image description here

var canvas = document.getElementById("canvas"); 
var ctx = canvas.getContext('2d'); 

var redRect = { 
    x: 33, 
    y: 33, 
    width: 200, 
    height: 60, 
    color: '#af0000' 
}; 
var blackRect = { 
    x: 77, 
    y: 66, 
    width: 120, 
    height: 60, 
    color: '#000' 
}; 
var blackRectHole = { 
    x: 110, 
    y: 80, 
    width: 20, 
    height: 20 
}; 
var cvRect = { 
    x: 0, 
    y: 0, 
    width: canvas.width, 
    height: canvas.height 
}; 


function drawRect(rect) { 
    ctx.beginPath(); 
    ctx.fillStyle = rect.color; 
    ctx.fillRect(rect.x, rect.y, rect.width, rect.height); 
    ctx.closePath(); 
} 

function drawRectClipped(rect, clipRect) { 
    ctx.save(); 
    clipOut(clipRect); 
    drawRect(rect); 
    ctx.restore(); 
} 

function clipOut(clipRect) { 
    ctx.beginPath(); 
    rectPath(cvRect); 
    ctx.lineTo(clipRect.x, clipRect.y); 
    rectPath_ccw(clipRect); 
    ctx.clip();  
} 

function rectPath(rect) { 
    ctx.moveTo(rect.x, rect.y); 
    ctx.lineTo(rect.x + rect.width, rect.y); 
    ctx.lineTo(rect.x + rect.width, rect.y + rect.height); 
    ctx.lineTo(rect.x, rect.y + rect.height); 
    ctx.lineTo(rect.x, rect.y); 
} 

function rectPath_ccw(rect) { 
    ctx.moveTo(rect.x, rect.y); 
    ctx.lineTo(rect.x, rect.y + rect.height); 
    ctx.lineTo(rect.x + rect.width, rect.y + rect.height); 
    ctx.lineTo(rect.x + rect.width, rect.y); 
    ctx.lineTo(rect.x, rect.y); 
} 

drawRect(redRect); 
drawRectClipped(blackRect, blackRectHole); 
+0

萬分感謝,煉金術士,陛下!需要在一個小時內分析代碼。 – Rossitten

相關問題