function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var dataURL = canvas.toDataURL("image/png");
return dataURL;
}
function main(src, cb) {
var image = new Image();
image.src = src + '?v=' + Math.random();
image.crossOrigin = "*";
image.onload = function () {
var base64 = getBase64Image(image);
cb && cb(base64);
}
}
main('http://192.168.0.204:8082/rest/v1/newdip/web/background/15.jpg', function (base64) {
document.querySelector(".box").style.backgroundImage = `url(${base64})`;
});
原文地址:http://www.cnblogs.com/minigrasshopper/p/9042686.html