1

为什么这个小脚本不起作用?

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<canvas id="can" height="500" width="500"></canvas>

<script type="text/javascript">

    var image = new Image().src="1.jpg";

    context = document.getElementById("can").getContext("2d");

    context.drawImage(image,10,10,480,480);

</script>

</body>
</html>

Firefox(最新版本)中的 Firebug 显示:

NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument arg 0 [nsIDOMCanvasRenderingContext2D.drawImage]
[Bei diesem Fehler anhalten]    

context.drawImage(image,10,10,480,480);

Chrome 也无法显示图像,他们只是说ERROR

4

2 回答 2

4

image.src 是异步的,你需要用回调来绘制它。

var image = new Image;
image.onload = function() { context.drawImage(image, 10, 10, 400, 400); }
image.src = .....
于 2012-09-07T19:25:31.063 回答
0

你需要做的就是改变:

   ctx.drawImage(i, 0, 0, arg.width, arg.height);

到:

   ctx.drawImage(arg.img, 0, 0, arg.width, arg.height);
于 2013-09-27T07:47:06.967 回答