这是我写的用于调整宽高比图像的代码,它适用于chrome但不在firefox上显示,有没有人知道什么是错误。
var image = new Image();
image.src = data;
//$(image).load(function () {
var aspectRatio = getAspectRatio(parseFloat($(image).prop('naturalWidth')),
parseFloat($(image).prop('naturalHeight')),
dstWidth,
dstHeight);
var canvas = document.createElement('canvas');
canvas.width = dstWidth;
canvas.height = dstHeight;
var x = (dstWidth - aspectRatio[0]) / 2;
var y = (dstHeight - aspectRatio[1]) / 2;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, x, y, aspectRatio[0], aspectRatio[1]);
return canvas.toDataURL("image/png");
这是canvas.toDataURL
生成的工作数据:图像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAAAQEAAADACAYAAAAEL9ZYAAAA1klEQVR4nO3BAQ0AAADCoPdPbQ8HFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwYD7QAB / UrDfgAAAABJRU5ErkJggg ==
答案 0 :(得分:3)
要使其工作,您需要处理图像加载的异步性质。您必须在此处使用回调机制。它在Chrome中“工作”的原因是偶然的;当您尝试使用和/或浏览器能够在您在drawImage调用中使用图像之前传递未压缩/解码的图像时,图像恰好位于缓存中。
对于大多数用户来说,这可能不起作用,所以要正确处理你可以做的加载 -
示例:
function getImageUri(url, callback) {
var image = new Image();
image.onload = function () { // handle onload
var image = this; // make sure we using valid image
var aspectRatio = getAspectRatio(parseFloat($(image).prop('naturalWidth')),
parseFloat($(image).prop('naturalHeight')),
dstWidth,
dstHeight);
var canvas = document.createElement('canvas');
canvas.width = dstWidth;
canvas.height = dstHeight;
var x = (dstWidth - aspectRatio[0]) / 2;
var y = (dstHeight - aspectRatio[1]) / 2;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, x, y, aspectRatio[0], aspectRatio[1]);
// use callback to provide the finished data-uri
callback(canvas.toDataURL());
}
image.src = url; // set src last
}
然后以这种方式使用它:
getImageUri(myURL, function (uri) {
console.log(uri); // contains the image as data-uri
});