我正在开发图像调整大小功能。我应该每次将图像缩小 25%,直到达到所需的尺寸。我尝试调试我的代码,但当图像已经加载并且我更改了 src 时,它似乎没有触发另一次加载。
generateData(data: File) {
const image = new Image();
image.src = URL.createObjectURL(data);
return Observable.fromEvent(image, 'load').map(e => {
let newWidth: number = image.width;
let canvas = document.createElement('canvas');
const ctx = canvas.getContext("2d");
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
while(newWidth > 2000) {
canvas = document.createElement('canvas');
const ctx = canvas.getContext("2d");
newWidth = newWidth * 0.75 >= 2000 ? newWidth * 0.75 : 2000;
const scale = newWidth / image.width;
image.width = newWidth;
image.height = image.height * scale;
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
image.src = canvas.toDataURL("image/png", 1);
}
const binStr = atob(canvas.toDataURL("image/png", 0.8).split(',')[ 1 ]);
const arr = new Uint8Array(binStr.length);
for(let i = 0; i < binStr.length; i++) { arr[ i ] = binStr.charCodeAt(i); }
const blob = new Blob([ arr ], { type: 'image/png' });
return new File([ blob ], data.name);
});
}
最佳答案
是的,每次更改 src
时,如果这是有效的 url,那么您将收到 .onload
事件:
image.onload event and browser cache
https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/image.onload
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images
document.addEventListener("DOMContentLoaded", function() {
var $image = document.getElementById("image");
$image.onload = function() { console.log("Image loaded."); }
setTimeout( () => $image.src = "http://finevintagedesign.com/sites/default/"+
"files/styles/uc_product_full/public/vo539b09c.jpg" , 3333 );
// This one set to the same URl
setTimeout( () => $image.src = "http://finevintagedesign.com/sites/default/"+
"files/styles/uc_product_full/public/vo539b09c.jpg" , 5555 );
});
img {
width:111px;
height:111px;
}
<img id="image" src="http://finevintagedesign.com/sites/default/files/styles/uc_product_full/public/vo539b09a.jpg"/>
关于javascript - 如果更改 HTMLImageElement 的 src 是否会再次触发加载事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49964138/