[英]javascript: I cannot draw an Image on my canvas
I already create my canvas on my page, however when I try to import an image on the canvas, it does not appear, here are the code I used. 我已经在页面上创建了画布,但是当我尝试在画布上导入图像时,它没有出现,这是我使用的代码。 (the makeGameArea is a method I used to create a canvas) (makeGameArea是我用来创建画布的方法)
var myGameArea = makeGameArea(700, 600, "myArea", "white");
var myContext = myGameArea.getContext("2d");
var myImage = new Image();
myImage.src = "sonic.gif";
myContext.drawImage(myImage, 100, 100, 100, 100);
Is there any syntax error in my code? 我的代码中有语法错误吗?
I am assuming you already have a canvas element on the page and that it has the id myArea. 我假设您已经在页面上有一个canvas元素,并且它的ID为myArea。
Your first line of javascript just does not make sense - unless you have a function called makeGameArea() which you haven't told us about, you cannot create a canvas in that in way. 您的JavaScript的第一行只是没有意义-除非您没有告诉过我们一个名为makeGameArea()的函数,否则您无法以这种方式创建画布。
Secondly you must load the image before you can draw it on the canvas. 其次,必须先加载图像,然后才能将其绘制在画布上。
Try this code out: 尝试以下代码:
var myGameArea = document.getElementById("myArea");
var myContext = myGameArea.getContext("2d");
myGameArea.width = 700;
myGameArea.height = 600;
var myImage = new Image();
myImage.onload = function() {
myContext.drawImage(myImage, 100, 100, 100, 100);
}
myImage.src = "sonic.gif";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.