javascript 画布 drawImage() 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18851976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:26:22  来源:igfitidea点击:

Canvas drawImage() not working

javascripthtmlcanvas

提问by Joe

This Javascript code draw part of the image on the canvas:

此 Javascript 代码在画布上绘制部分图像:

var img = document.getElementById('img');
var canvas = document.getElementById('can');
//canvas.width = img.width;
//canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

But when I uncomment the middle lines to set the canvas width and height, the drawImage() does not work. What should I check in order to find the problem?

但是当我取消注释中间线以设置画布宽度和高度时,drawImage() 不起作用。我应该检查什么才能找到问题?

回答by letiagoalves

You need to wait for the browser to load the image.

您需要等待浏览器加载图像

Use onloadevent if image was not yet loaded and change your code to something like this:

onload如果图像尚未加载,请使用事件并将您的代码更改为如下所示:

var img = document.getElementById('img');
var canvas = document.getElementById('can');
var ctx = canvas.getContext("2d");

var callback = function(image) {
   if(!image) image = this;
   canvas.width = img.width;
   canvas.height = img.height;
   ctx.drawImage(image, 0, 0);
}

if(img.complete) { //check if image was already loaded by the browser
   callback(img);
}else {
   img.onload = callback;
}

See this working demo

看到这个工作演示

回答by Joe

var img = document.getElementById('img');

Try naming the variable something else. Also make sure some image is loaded.

尝试将变量命名为其他名称。还要确保加载了一些图像。

Try my fiddle http://jsfiddle.net/aliasm2k/tAum2/for more ideas

试试我的小提琴http://jsfiddle.net/aliasm2k/tAum2/了解更多想法

回答by Arnau Lacambra

The width and height image attributes aren't set until the image is loaded, so i propose you to put your code in onLoad() image event.

在加载图像之前不会设置宽度和高度图像属性,因此我建议您将代码放在 onLoad() 图像事件中。