-
-
Notifications
You must be signed in to change notification settings - Fork 117
获取图片原始尺寸 #39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
第一行代码就错了吧。。 |
之前也写过一篇,不借助ImageElement的 iamgqb/I-should-know#2 |
其实 |
这里js执行比发起网络请求要快,所以不会影响吧。但放到前面会保险一些 |
如果 image 的 <img src="path.png" width="100" height="100" alt="image" /> or const image = new Image()
image.width = 100
image.height = 100
image.src = 'path.png' 应该只能依据 export default function(image: HTMLImageElement) {
return new Promise((resolve, reject) => {
if (image.naturalWidth) {
resolve({ width: image.naturalWidth, height: image.naturalHeight })
}
const savedImage = new Image()
savedImage.onload = () => {
resolve({ width: savedImage.width, height: savedImage.height })
}
savedImage.onerror = err => {
reject(err)
}
savedImage.src = image.src
})
} |
这句应该是不对的吧。看上去像是支持 DOM 和 选择器,但是其实并不会执行选择器部分。
或者是直接删掉?或者是应该判断是img是字符串,然后就去querySelector |
@github-linong 是的。 function getImgRawSize(img: HTMLImageElement | string): Promise<{ width: number; height: number }> {
const $img: HTMLImageElement = typeof img === 'string' ? document.querySelector(img) : img;
return new Promise((resolve, reject) => {
if ($img.naturalWidth) {
resolve({ width: $img.naturalWidth, height: $img.naturalHeight });
}
if ($img.complete && !$img.getAttribute('width') && !$img.getAttribute('height')) {
resolve({ width: $img.width, height: $img.height });
}
const image = new Image;
image.onload = () => {
resolve({ width: image.width, height: image.height })
}
image.onerror = reject;
image.src = $img.src;
})
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: