我想将所有图像转换为base64 url。这是脚本。
var convert = function(url, callback) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL();
callback(dataURL);
canvas = null;
};
img.src = url;
}
var imgs = document.getElementsByTagName('img');
for (var x = 0; x < imgs.length; x++) {
var urls = imgs[x].getAttribute('src');
convert(urls, function(base64) {
imgs[x].setAttribute('src', base64);
});
}
但是我得到了这个错误:
未捕获的TypeError:无法读取未定义的属性'setAttribute'
我认为回调有问题,但我不知道如何解决。