最近项目中有一个裁切图片的需求,百度了一番最后选用cropperImage插件。
由于项目中图片是存放在阿里云上,cropperImage插件在初始化默认图的时候会存在跨域问题,百度经验我选择了将图片转换成了base64
代码如下:
//将图片转换成base64 const transBase64FromImage = (image) => { console.log("image", image); let canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; let ctx = canvas.getContext("2d"); ctx.drawImage(image, 0, 0, image.width, image.height); // // 可选其他值 image/jpeg return canvas.toDataURL("image/png"); };
// 将转换成base64的图片设置成可跨域 const setAvatarBase64 = (src) => { return new Promise((resolve, reject) => { let image = new Image(); // 处理缓存 image.src = src + "?v=" + Math.random(); // 支持跨域图片 image.crossOrigin = "*"; image.onload = () => { let base64 = transBase64FromImage(image); resolve(base64); }; }); };
标签:canvas,跨域,image,base64,插件,图片 From: https://www.cnblogs.com/junechen/p/16965315.html