2017-09-01 204 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>