Javascript新图像()维度
我有一个画在画布上的对象,但我似乎无法获得图像的尺寸(宽度/高度)Javascript新图像()维度,javascript,canvas,Javascript,Canvas,我有一个画在画布上的对象,但我似乎无法获得图像的尺寸(宽度/高度) var rawr = { x: 0, y: 0, speed: 4, height:0, img: new Image(), url: "https://www.google.co.uk/images/srpr/logo11w.png", init: function() { this.img.src=this.url; this.hei
var rawr = {
x: 0,
y: 0,
speed: 4,
height:0,
img: new Image(),
url: "https://www.google.co.uk/images/srpr/logo11w.png",
init: function() {
this.img.src=this.url;
this.height=this.img.height;
},
draw: function() {
canvas.drawImage(this.img,this.x,this.y);
},
move: function() {
if(this.y>CANVAS_HEIGHT)
{
this.y=this.height*-1;
}
this.y+=this.speed;
}
};
基本上,这个.height
仍然是最初定义的零。我如何纠正这个问题
提前感谢,,
蒂姆。如果我读对了,您将在设置src后立即检查高度。尝试在onLoad事件处理程序中执行此操作,以便它等待图像加载,然后调整图像标记的大小,否则它不知道高度。如果我读得正确,则在设置src后立即检查高度。尝试在onLoad事件处理程序中执行此操作,以便它等待图像加载,然后调整图像标记的大小,否则它不知道图像的高度。在利用图像的高度之前,等待图像的onLoad触发。大概是这样的:
var imagePreloaded = this.img;
imagePreloaded.onload(function(){
var height = imagePreloaded.height;
})
等待图像加载触发,然后再利用其高度。大概是这样的:
var imagePreloaded = this.img;
imagePreloaded.onload(function(){
var height = imagePreloaded.height;
})
我已将此标记为正确答案,因为它几乎就是我需要的解决方案。如果我
alert(imagepreload.height)
我得到了我需要的结果,但是当我尝试this.height=imagepreload.height时代码>它似乎没有设置值。有什么建议吗?此
位于匿名函数的不同范围内。我已将此标记为正确答案,因为它几乎就是我需要的解决方案。如果我alert(imagepreload.height)
我得到了我需要的结果,但是当我尝试this.height=imagepreload.height时代码>它似乎没有设置值。有什么建议吗?此
位于匿名函数的不同范围内。