2012-03-18 98 views
1

我想在畫布上顯示圖像(HTML5),以便稍後將其拖放。這是我如何開始的,我使用了一個在Canvas上繪製的圓形形狀,然後我希望它的背景紋理是在此粘貼代碼的外部定義的圖像。 現在我已經知道在x = 0,y = 0位置繪製紋理/圖像。因爲我必須使用'no-repeat'參數爲createPattern()方法(圖片將啓用drag'n'drop),所以我必須創建模式的位置circle.x,circle.y(這些更改拖放)。我怎樣才能讓模式被繪製在不是(0,0)的位置; ?HTML5 - createPattern(..) - 動態位置(x,y)

如果您知道任何更好的解決辦法,然後我打開有人說,一張圖片勝過千言萬語,所以在圖片上我將它解釋爲這樣的建議

enter image description here

var ctx, circle; 

    function draw(){  
     ctx.clearRect(0, 0, canvas.width, canvas.height); 
     ctx.beginPath();     
     ctx.arc(circle.x+imageObj.width/2,circle.y+imageObj.height/2,circle.r,0,Math.PI*2,false); 
     var pattern = ctx.createPattern(imageObj, 'no-repeat'); 
     ctx.fillStyle = pattern; 
     ctx.fillRect(circle.x,circle.y, imageObj.width, imageObj.height); 
    } 


window.onload = function(){ 
    canvas = document.getElementById('area'); 
    ctx = canvas.getContext('2d'); 

    circle = { 
     x: canvas.width/2, 
     y: canvas.height/2, 
     r: 50 
    } 

    draw();  
}; 
+0

我應該使用translate(x,y)函數嗎? – 2012-03-18 00:53:43

回答

0

好吧,我找到了一種方法,這就是我想要的。如果你們知道任何其他方式,請提交您的答案

var ctx, circle; 

     function draw(){  
      ctx.clearRect(0, 0, canvas.width, canvas.height); 
      ctx.beginPath();     
      ctx.arc(circle.x+imageObj.width/2,circle.y+imageObj.height/2,circle.r,0,Math.PI*2,false); 
      ctx.drawImage(imageObj, circle.x, circle.y, imageObj.width, imageObj.height); 
     } 


    window.onload = function(){ 
     canvas = document.getElementById('area'); 
     ctx = canvas.getContext('2d'); 

     circle = { 
      x: canvas.width/2, 
      y: canvas.height/2, 
      r: 50 
     } 

     draw();  
    };