图像未显示在画布上 [英] Image doesn't show up on canvas
本文介绍了图像未显示在画布上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 canvas
元素,但是由于某种原因,它无法显示我的图像.
I'm experimenting with the canvas
element, but for some reason it doesn't display my image.
我使用以下代码:
function Canvas() {
this.field = function() {
var battlefield = document.getElementById('battlefield');
var canvas = battlefield.getElementsByTagName('canvas')[0];
return canvas.getContext('2d');
}
}
function Draw(canvas) {
if (!canvas) {
alert('There is no canvas available (yet)!');
return false;
}
this.canvas = canvas;
this.grass = function(pos_x, pos_y) {
var terrain = new Terrain();
var specs = terrain.grass();
var img = new Image();
img.onload = function(){
canvas.drawImage(img, specs.position_x, specs.position_y, specs.dimension_x, specs.dimension_y, pos_x, pos_y, specs.dimension_x, specs.dimension_y);
console.log('success???'); // this is being output
};
img.src = '/img/terrain.png';
}
}
(function() {
var canvas = new Canvas();
var draw = new Draw(canvas.field());
draw.grass();
})();
没有错误,但是图像不显示.我已经验证了该图像是否存在并且确实存在.我还验证了 specs
,它们确实包含应有的内容:
There are no errors, but the image just doesn't display. I've verified if the image exists and it does. I also verified the specs
and they do contain what they should:
dimension_x: 25
dimension_y: 25
position_x: 0
position_y: 0
知道我在做什么错吗?
推荐答案
pos_x
和 pos_y
在您的代码中为 undefined
.如果您将它们的值传递给 draw.grass()
:
pos_x
and pos_y
are undefined
in your code. It works if you pass values for them to draw.grass()
:
draw.grass(0, 0);
在Chrome和Firefox中进行了测试.
Tested in Chrome and Firefox.
这篇关于图像未显示在画布上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文