简体   繁体   English

如何获取存储在javascript对象中的图像的宽度和高度?

[英]How do I get the width and height of an image stored inside a javascript object?

I am looking of a way to find the dimensions of the passed in image. 我正在寻找一种方法来找到传递的图像的尺寸。 When I log the height and width it returns 0 for both. 当我记录高度和宽度时,两者都返回0。

function GamePiece(imageName){
    this.image = new Image();
    this.image.src = imageName;
    this.width = this.image.width;
    this.height = this.image.height;
}

You need to allow the browser time to load the image before you can get it's size. 您需要等待浏览器时间来加载图像,然后才能获取图像的大小。 You can use the onload callback to detect when the image is loaded. 您可以使用onload回调检测何时加载映像。

function GamePiece(imageName){
    var gamePiece = this;

    this.image = new Image();
    this.image.onload = function() {
        gamePiece.width = this.width;
        gamePiece.height = this.height;
    }
    this.image.src = imageName;
}

There will be a delay before the callback is run and the dimensions are set on your object. 在运行回调和在对象上设置尺寸之前会有一个延迟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 javascript 中的 object 获取宽度和高度值 - how do I get the width and height values from this object in javascript 如何使用javascript从文件获取图像尺寸(高度,宽度) - How do i get the image dimensions (height, width) from a file by using javascript 如何从 html 输入标签创建图像 object 并获取其宽度/高度? - How do I create an image object from an html input tag and get its width/height? KineticJS:如何获取Sprite或图片的宽度和高度? - KineticJS: How do I get the Width and Height of a Sprite or Image? 如何使用 JavaScript 获取图像的宽度和高度? - How to get the width and height of my image with JavaScript? 如何获取 javascript 中图像的高度和宽度? - how to get the height and width of image in javascript? 如何将图像保持在具有固定宽度和高度的div内,而将其余图像隐藏起来? - How do I keep an image inside a div with a set width and height, but keep the rest of the image hidden? 如何使用JavaScript在HTML中的TextArea中获取文本宽度和高度? - How to get text width and height inside a TextArea in HTML using JavaScript? 如何在加载之前获取JavaScript的图像宽度和高度? - How to get in JavaScript width and height of image, before it's loaded? JavaScript如何从XMLHttpRequest获取图像的宽度和高度 - JavaScript How to get an image width and height from an XMLHttpRequest
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM