Javascript。为什么这个代码不起作用? 我不能称物业高度为:
调用height属性时,消息获取0。但它应该给我1152Javascript。为什么这个代码不起作用? 我不能称物业高度为:,javascript,html5-canvas,Javascript,Html5 Canvas,调用height属性时,消息获取0。但它应该给我1152 var fondoJuego=new FondoJuego(); fondoJuego.setFondoSrc("tituloNV.png"); alert("Altura "+fondoJuego.getFondo().height); var FondoJuego=function(){ this.fondo=new Image(); this.getFondo=function(){
var fondoJuego=new FondoJuego();
fondoJuego.setFondoSrc("tituloNV.png");
alert("Altura "+fondoJuego.getFondo().height);
var FondoJuego=function(){
this.fondo=new Image();
this.getFondo=function(){
return this.fondo;
};
this.getFondoSrc=function(){
return this.fondo.src;
};
this.setFondo=function(fondoAux){
this.fondo=fondoAux;
};
this.setFondoSrc=function(fondoSrcAux){
this.fondo.src=fondoSrcAux;
};
};
感谢这是因为图像以
异步方式加载需要一些时间
让我们以谷歌的涂鸦为例:
var imageAsync = new Image();
imageAsync.src = "https://www.google.com.br/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png?t=" + (+new Date);
console.log(imageAsync.height);
var imageSync = new Image();
imageSync.src = "https://www.google.com.br/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png?t=" + (+new Date);
imageSync.onload = function () {
console.log(this.height);
}
返回0和92。您需要收听加载事件
这应该起作用:
function getHeight() {
alert("Altura " + fondoJuego.fondo.height );
return true;
}
var FondoJuego = function() {
this.fondo = new Image();
this.fondo.addEventListener("load", function(){
getHeight();
});
this.getFondo=function(){
return this.fondo;
};
this.getFondoSrc=function(){
return this.fondo.src;
};
this.setFondo=function(fondoAux){
this.fondo=fondoAux;
};
this.setFondoSrc=function(fondoSrcAux){
this.fondo.src=fondoSrcAux;
};
};
var fondoJuego = new FondoJuego();
fondoJuego.setFondoSrc("tituloNV.jpg");
检查此JSFIDLE:可能是因为运行getFondo()
时图像尚未检索,因此没有可用的高数据。设置src
是异步的-立即继续执行,当脚本的其余部分运行时,图像将在后台加载。png是否与包含此脚本的文件位于同一路径上?是的,它位于同一路径上。用这个代码解决。“imageAsync.onload=function(){console.log(this.height);}”谢谢。谢谢你帮助我!SolvedRemember,如果答案解决了您的问题,请接受@Moses91