2012-07-28 34 views
2

我想使一個圖像在畫布上繪製的網站,然後用戶能夠按下按鈕ctx.fill()的某些部分與顏色。我遇到了問題,我只能ctx.fill()最近創建的形狀,往往不是我想要的形狀。HTML5畫布 - 如何填充()特定的上下文

下面是一個例子。在這段代碼中(我住在http://build.rivingtondesignhouse.com/piol/test/),我試圖繪製第一個矩形,然後將它保存到堆棧中,然後繪製第二個矩形(並且不保存它),然後調用fill()函數時我想用不同的模式恢復()第一個矩形和ctx.fill()。它不起作用!在實踐中,我實際上試圖用用戶在繪製圖像之後選擇的任何顏色來填充這個複雜形狀的灰色部分,但我認爲這種技術是相同的。 (http://build.rivingtondesignhouse.com/piol/test/justTop.html)

在此先感謝您的幫助!

下面的代碼:

<script type="text/javascript"> 
var canvas; 
var ctx; 

function init() { 
    canvas = document.getElementById("canvas"); 
    ctx = canvas.getContext("2d"); 
    draw(); 
} 


function draw() { 
    ctx.fillStyle = '#FA6900'; 
    ctx.shadowOffsetX = 5; 
    ctx.shadowOffsetY = 5; 
    ctx.shadowBlur = 4; 
    ctx.shadowColor = 'rgba(204, 204, 204, 0.5)'; 
    ctx.fillRect(0,0,15,150); 
    ctx.save(); 

    ctx.fillStyle = '#E0E4CD'; 
    ctx.shadowOffsetX = 10; 
    ctx.shadowOffsetY = 10; 
    ctx.shadowBlur = 4; 
    ctx.shadowColor = 'rgba(204, 204, 204, 0.5)'; 
    ctx.fillRect(30,0,30,150); 
} 

function fill(){ 
    var image = new Image(); 
    image.src = "http://www.html5canvastutorials.com/demos/assets/wood-pattern.png"; 
    image.onload = drawPattern; 
    function drawPattern() { 
     ctx.restore(); 
     ctx.fillStyle = ctx.createPattern(image, "repeat"); 
     ctx.fill(); 
    } 
} 

init(); 

+0

http://jsfiddle.net/BJTzx/這應該讓你開始!最好.. – Shouvik 2012-07-28 16:59:52

+0

謝謝。這是我發佈的代碼不起作用,但在JSFiddle中。你能幫我找到解決方案嗎? – user1559817 2012-07-28 18:43:28

+0

右鍵點擊你看到它在小提琴上工作的地方。您應該能夠看到HTML的來源。它脫穎而出...複製粘貼,並與你做錯了什麼比較。 (提示,檢查結果部分的來源!) – Shouvik 2012-07-28 19:18:25

回答

1

有跡象表明,我們需要清理之前,我可以回答這個問題的幾個誤解。

save()restore()不保存和恢復畫布位圖。相反,他們保存並恢復在畫布上下文中設置的所有屬性,這就是全部!

例如

ctx.fillStyle = 'red'; 
ctx.save(); // save the fact that the fillstyle is red 
ctx.fillStyle = 'blue'; // change the fillstyle 
ctx.fillRect(0,0,5,5); // draws a blue rectangle 
ctx.restore(); // restores the old context state, so the fillStyle is back to red 
ctx.fillRect(10,0,5,5); // draws a red rectangle // draws a red rectangle 

請參閱代碼直播here

所以你不是通過調用save()來保存一個矩形(或任何繪製的)。您可以保存位圖的唯一方法是將其繪製(或其中的一部分)到另一個畫布(使用anotherCanvasContext.drawImage(canvasIWantToSave, 0, 0)),或者通過保存足夠的信息來使用適當的更改重新繪製整個場景。

這裏是你能重新構造一種方式的代碼示例,以便它你想要做什麼:http://jsfiddle.net/xwqXb/

+0

我想,你也可以通過將它「序列化」成一個字符串來調用'toDataURL',從畫布上「保存」位圖。 – trejder 2014-01-22 21:04:53