因为图片资源放到OSS上,一般情况下img的src是不存在这个问题的,但是因为需要图片合成,需要拿到图片资源后进行处理,比如前段canvas图片合成,避免不了会出现跨域情况。
合成代码如下:
var img = document.createElement_x('img');
img.src = res.img_url;
img.onload = function(){
var code = document.createElement_x('img');
code.src = res.code_url;
code.onload = function(){
var canvas = document.createElement_x('canvas');
var context = canvas.getContext("2d");
canvas.width = 750;
canvas.height = 1334;
context.drawImage(img,0,0,img.width,img.height,0,0,750,1334);
context.drawImage(code,0,0,code.width,code.height,554,1068,180,180);
context.font="bolder 20px 黑体";
context.textAlign="center";
context.fillText("name",644,1268);
url = canvas.toDataURL();
t.shareUrl = url;
}
}
此时出现错误
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. at HTMLImageElement.code.onload
因为域名不在同一域名下,导致资源获取失败。
解决方案一
img对象添加 crossOrigin = '*';使用CORS 请求,可以实现跨域访问资源
var img = document.createElement_x('img');
img.src = res.img_url;
img.crossOrigin = 'anonymous';
img.onload = function(){
var code = document.createElement_x('img');
code.src = res.code_url;
code.crossOrigin = 'anonymous';
code.onload = function(){
var canvas = document.createElement_x('canvas');
var context = canvas.getContext("2d");
canvas.width = 750;
canvas.height = 1334;
context.drawImage(img,0,0,img.width,img.height,0,0,750,1334);
context.drawImage(code,0,0,code.width,code.height,554,1068,180,180);
context.font="bolder 20px 黑体";
context.textAlign="center";
context.fillText("name",644,1268);
url = canvas.toDataURL();
t.shareUrl = url;
}
}
代码执行出现如下错误:
Access to image at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
此时需要后端解决,让后端人员添加header头 Access-Control-Allow-Origin 与 Access-Control-Allow-Methods 允许跨域访问资源。
以上代码可以解决大部分问题,但是,有些手机,比如某果或者部分浏览器不支持crossOrigin ,此时需要方案二
方案二如下
axios.get(res.static_customize_poster,{
responseType: 'blob'
}).then(function(data){
var img = document.createElement_x('img');
img.src = URL.createObjectURL(data.data);
img.onload = function(){
var code = document.createElement_x('img');
code.src = res.code;
code.crossOrigin = 'anonymous';
code.onload = function(){
var canvas = document.createElement_x('canvas');
var context = canvas.getContext("2d");
canvas.width = 750;
canvas.height = 1334;
context.drawImage(img,0,0,img.width,img.height,0,0,750,1334);
context.drawImage(code,0,0,code.width,code.height,554,1068,180,180);
context.font="bolder 20px 黑体";
context.textAlign="center";
context.fillText("name",644,1268);
url = canvas.toDataURL();
t.shareUrl = url;
}
}
});
先异步请求图片资源,设置响应类型为responseType为blob,使用URL.createObjectURL将blob转换为可用blob:url
然后执行正常程序即可