Javascript 从屏幕外画布在可见画布上绘制
当我尝试使用屏幕外画布上的图像在可见画布上绘制时,会出现奇怪的错误,直到我以某种方式重新加载页面,图像才会绘制 下面是我的示例代码。插入任何小图像文件Javascript 从屏幕外画布在可见画布上绘制,javascript,html,canvas,html5-canvas,Javascript,Html,Canvas,Html5 Canvas,当我尝试使用屏幕外画布上的图像在可见画布上绘制时,会出现奇怪的错误,直到我以某种方式重新加载页面,图像才会绘制 下面是我的示例代码。插入任何小图像文件 <!DOCTYPE HTML> <html> <head> </head> <body> <canvas id="visible canvas" width=800 height=600></canvas> <script>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas id="visible canvas" width=800 height=600></canvas>
<script>
// load the image
var img = new Image();
img.src = "smallimage.png";
// create a hidden canvas, exactly the size of our small image
var hidden_canvas = document.createElement("canvas");
hidden_canvas.width = img.width;
hidden_canvas.height = img.height;
var hidden_context = hidden_canvas.getContext("2d");
// draw the image on the hidden canvas
hidden_context.drawImage(img, 0, 0);
// set up the visible canvas
var visible_canvas = document.getElementById("visible canvas");
var visible_context = visible_canvas.getContext("2d");
// draw on the visible canvas using the image from the hidden canvas
visible_context.drawImage(hidden_canvas,0,0);
</script>
</body>
</html>
//加载图像
var img=新图像();
img.src=“smallimage.png”;
//创建一个隐藏的画布,正好是我们的小图像的大小
var hidden_canvas=document.createElement(“canvas”);
隐藏宽度=img.width;
隐藏高度=img.height;
var hidden_context=hidden_canvas.getContext(“2d”);
//在隐藏的画布上绘制图像
隐藏的上下文drawImage(img,0,0);
//设置可见画布
var visible_canvas=document.getElementById(“可视画布”);
var visible_context=visible_canvas.getContext(“2d”);
//使用隐藏画布中的图像在可见画布上绘制
可见的上下文.drawImage(隐藏的画布,0,0);
在Firefox中,我第一次加载页面时,会看到一个空白页面,Firebug中出现以下错误:
InvalidStateError:试图使用不可用或不再可用的对象
。它说错误出现在最后一行:visible\u context.drawImage(hidden\u canvas,0,0)代码>
然后我刷新页面,它就可以正常工作了
在Chrome中,我也会得到一个空白页面(没有错误)。如果我在地址栏中按enter键,它将再次加载并正常工作
我已经尝试从本地服务器运行,但仍然得到相同的结果
有人能帮我理解这个问题吗?为什么在我第一次加载页面时它就不起作用了?这是因为在加载图像之前,您的其余代码正在运行。它可以在重新加载时工作,因为图像是缓存的,所以会立即加载
使用iamge的onload属性设置加载事件侦听器,并在映像准备就绪时执行代码
var img = new Image();
img.onload = function(){
// create a hidden canvas, exactly the size of our small image
var hidden_canvas = document.createElement("canvas");
hidden_canvas.width = img.width;
hidden_canvas.height = img.height;
var hidden_context = hidden_canvas.getContext("2d");
// draw the image on the hidden canvas
hidden_context.drawImage(img, 0, 0);
// set up the visible canvas
var visible_canvas = document.getElementById("visible canvas");
var visible_context = visible_canvas.getContext("2d");
// draw on the visible canvas using the image from the hidden canvas
visible_context.drawImage(hidden_canvas,0,0);
};
img.src = "http://placehold.it/250x250";
)