2017-09-01 153 views
0

考慮下面的代碼繪製飛船圖像:繪製圖像

 // Get a handle to the image object 
     var image = document.getElementById('spaceship'); 

     // Draw the image at (0,350) 
     context.drawImage(image,0,350); - error on this line 

     // Scaling the image to half the original size 
     context.drawImage(image,0,400,100,25); 

     // Drawing part of the image 
     context.drawImage(image,0,0,60,50,0,420,60,50); 

在這個腳本後,HTML有這樣的代碼:

 <img src = "spaceship.png" id = "spaceship"> 

我使用與書中圖像不同的圖像,但大概是實際的圖像並不重要(已經測試了圖像本身)。第二行有錯誤:context.drawImage(image,0,350); - 未定義未捕獲的引用錯誤上下文。

語境以前曾定義:

  var context = canvas.getContext('2d'); 

而且它已經爲許多其他形狀,但在該行的錯誤工作。

回答

0

您需要在頁面上放置一個canvas元素,使用javascript獲取它,然後從中獲取上下文,然後使用。就像這樣:

HTML:

<canvas id="myCanvas" width="200" height="100"></canvas> 

的JavaScript:

var c = document.getElementById("myCanvas"); 
var ctx = c.getContext("2d"); 
0

這是在充分代碼:

<body onload = "pageLoaded();"> 
    <canvas width = "640" height = "480" id = "testcanvas" style = "border:black 1px solid;"> 
    <script type = "text/javascript" charset = "utf-8"> 
     function pageLoaded() { 
     var canvas = document.getElementById('testcanvas'); 
     var context = canvas.getContext('2d'); 




     // Get a handle to the image object 
     var image = document.getElementById('spaceship'); 

     // Draw the image at (0,350) 
     context.drawImage(image,0,350); 

     // Scaling the image to half the original size 
     context.drawImage(image,0,400,100,25); 

     // Drawing part of the image 
     context.drawImage(image,0,0,60,50,0,420,60,50); 










    </script> 

    </canvas> 
    <img src="spaceship.png" id="spaceship"> 

</body>