2012-12-13 17 views
1

如何用JavaScript創建一個形狀的圖像?你如何填寫一個形象在JavaScript中創建一個形象?

我正在使用我用javascript創建的形狀,現在正在填充顏色。我怎樣才能取代它,並用我選擇的圖像/ gif填充它?

function shape(x,y) { 

     ctx.fillStyle = "#9dd4ff"; 
     ctx.beginPath(); 
     ctx.moveTo(232,213) 
     ctx.lineTo(315,198); 
     ctx.lineTo(x,y); 
     ctx.closePath(); 
     ctx.fill(); 
} 
+1

是什麼CTX解決這個問題?我想你應該嘗試給一些圖像代替正在使用的顏色代碼的路徑? – Prateek

+0

@pKs - 'ctx'是指我猜的'canvas'。 –

+0

畫布的*上下文*,可能。 @ user1899948,當你說「填充」時,圖像是否會重複?你是在繪製一個形狀,然後想要僅在該形狀的上下文中繪製,或者其他東西? – JayC

回答

0

試試這個:

var thumbImg = document.createElement('img'); 

thumbImg.src = 'path_to_image'; 



function shape(x,y) { 

     ctx.fillStyle = "#9dd4ff"; 
     ctx.beginPath(); 
     ctx.moveTo(232,213) 
     ctx.lineTo(315,198); 
     ctx.lineTo(x,y); 


     ctx.drawImage(thumbImg, 0, 0, 50, 50); 

     ctx.closePath(); 
     ctx.fill(); 
} 

- 編輯 -

刪除ctx.fillStyle ="#9dd4ff"

當你需要提及圖片的路徑。

1

您可以使用您的路徑作爲掩模

這裏是代碼

// Create an image element 
var img = document.createElement('IMG'); 
// When the image is loaded, draw it 
img.onload = function() { 
    // Save the state, so we can undo the clipping 
    ctx.save(); 
    // Create a shape, of some sort 
    ctx.beginPath(); 
    ctx.moveTo(10, 10); 
    ctx.lineTo(100, 30); 
    ctx.lineTo(180, 10); 
    ctx.lineTo(200, 60); 
    ctx.arcTo(180, 70, 120, 0, 10); 
    ctx.lineTo(200, 180); 
    ctx.lineTo(100, 150); 
    ctx.lineTo(70, 180); 
    ctx.lineTo(20, 130); 
    ctx.lineTo(50, 70); 
    ctx.closePath(); 
    // Clip to the current path 
    ctx.clip(); 
    ctx.drawImage(img, 0, 0); 
    // Undo the clipping 
    ctx.restore(); 
} 
// Specify the src to load the image 
img.src = "https://www.google.com/images/srpr/logo3w.png";