2012-10-18 54 views
2

我想知道是否有人可以幫助我弄清楚如何使用HTML5 Canvas和JavaScript在圖像上繪製對象?如何使用HTML5 Canvas和JavaScript將圖形對象顯示在圖像上?

我已經寫了一個例子來顯示我的問題在下面(只要你有一個名爲choc.jpg的圖像可用它應該工作)。我希望香蕉物體出現在JPEG上,但它不會。我是HTML5和canvas的新手,並且非常欣賞被指向正確的方向。 非常感謝您的幫助!

<!DOCTYPE HTML> 
<script> 

window.onload=function() { 
var testcanvas=document.getElementById("bananaDesign"); 
var testcontext=testcanvas.getContext('2d'); 

//set a background image 
/* if I comment out this section no image appears and the banana gets drawn. How do I get banana to go over image? */ 

var importedImg = new Image(); 
importedImg.src = 'pictures/choc.JPG'; 
importedImg.onload = function(){ 
testcontext.drawImage(importedImg, 10, 10); 
}; 


//draw a banana 
testcontext.fillStyle = "#FFA824"; 
testcontext.beginPath(); 
testcontext.moveTo(62,20); 
testcontext.lineTo(80,20); //2 
testcontext.lineTo(80,30); //3 
testcontext.lineTo(90,50); //4 
testcontext.lineTo(80,85); //5 
testcontext.lineTo(45,95); //6 
testcontext.lineTo(40,80); //7 
testcontext.lineTo(60,60); //8 
testcontext.lineTo(60,30); //9 
testcontext.fill(); 
} 

</script> 


<canvas id="bananaDesign" width="500" height="600" style="border: 5px red solid"> 
<p>Your browser does not display HTML5 canvas. Please update to view this design.</p> 
</canvas> 

回答

1

圖像異步加載,因此在繪製香蕉(因此在它上面)之後實際將其拖到畫布上。一個快速的解決將是移動你的香蕉抽獎代碼到你的圖像加載處理程序,您所繪製圖像畫布後(見http://jsfiddle.net/5pGqV/,回想起來我選擇背景圖片是不理想;)):

<!DOCTYPE HTML> 
<script> 

    window.onload=function() { 
     var testcanvas=document.getElementById("bananaDesign"); 
     var testcontext=testcanvas.getContext('2d'); 

     //set a background image 
     /* if I comment out this section no image appears and the banana gets drawn. How do I get banana to go over image? */ 

     var importedImg = new Image(); 
     importedImg.src = 'pictures/choc.JPG'; 
     importedImg.onload = function(){ 

      //draw the loaded image to canvas first 
      testcontext.drawImage(importedImg, 10, 10); 

      //now draw a banana on top 
      testcontext.fillStyle = "#FFA824"; 
      testcontext.beginPath(); 
      testcontext.moveTo(62,20); 
      testcontext.lineTo(80,20); //2 
      testcontext.lineTo(80,30); //3 
      testcontext.lineTo(90,50); //4 
      testcontext.lineTo(80,85); //5 
      testcontext.lineTo(45,95); //6 
      testcontext.lineTo(40,80); //7 
      testcontext.lineTo(60,60); //8 
      testcontext.lineTo(60,30); //9 
      testcontext.fill(); 
     }; 
    } 

</script> 


<canvas id="bananaDesign" width="500" height="600" style="border: 5px red solid"> 
<p>Your browser does not display HTML5 canvas. Please update to view this design.</p> 
</canvas> 
+0

非常感謝你的幫助,給了我一個替代的解決方案:-)這個工作太棒了! –

1

您需要在上下文中配置globalCompositeOperation屬性。 在您的案例中,將值設置爲'destination-over'以繪製圖片。 以下是所有可能值列表http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-globalcompositeoperation

與示例代碼http://jsfiddle.net/gU4xc/

+0

非常感謝您的回答,這正是我所追求的目標,同時也指引我走向正確的方向,以便更好地理解合成。非常感謝! –

相關問題