这段时间在做一个分享的页面,其中有一个步骤就是
1.需要将服务端的几张图片合成一张图片;
2.几种图片中包含了二维码信息;
3.二维码的信息展示在右下角。
合成图片的过程就是调用了canvas的API,代码如下:
_buildImages(config, callback) {
CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) {
var min_size = Math.min(w, h);
if (r > min_size / 2) r = min_size / 2;
// 开始绘制
this.beginPath();
this.moveTo(x + r, y);
this.arcTo(x + w, y, x + w, y + h, r);
this.arcTo(x + w, y + h, x, y + h, r);
this.arcTo(x, y + h, x, y, r);
this.arcTo(x, y, x + w, y, r);
this.stroke();
this.closePath();
return this;
}
// 使用canvas
let myCanvas = document.createElement("canvas");
myCanvas.style.backgroundColor = 'transparent';
myCanvas.width = config.width;
myCanvas.height = config.height;
let context = myCanvas.getContext("2d");
context.save();
// 图片的image对象放回原来的数组中。
let items = config.items;
for (let i = 0; i < items.length; i++) {
let item = items[i];
let img = new Image();
img.crossOrigin = "anonymous";
img.src = item.src;
item.imageObj = img;
}
// 定时判断图片是否加载完成
let window_setThree = window.setInterval(function() {
//图片是否全部加在完成的标志
let allReady = true;
//判断图片是否全部加在完成
for (let i = 0; i < items.length; i++) {
let image = items[i].imageObj;
allReady = allReady && image.complete
}
// 拼接图片,输出dataUrl
if (allReady) {
clearInterval(window.clearInterval(window_setThree));
for (let i = 0; i < items.length; i++) {
let item = items[i];
//处理服务端传过来没有头像的问题
if(!config.items[i].src){
continue;
}
if(i == 1){
context.save();
var pattern = context.createPattern(item.imageObj, "no-repeat");
context.roundRect(item.xpw * config.width, item.yph * config.height, item.wpw * config.width, item.hph * config.height, item.hph * config.height/2);
context.fillStyle = pattern;
context.fill();
context.clip();
context.drawImage(item.imageObj, item.xpw * config.width, item.yph * config.height, item.wpw * config.width, item.hph * config.height);
context.restore(); // 还原状态
}else{
context.drawImage(item.imageObj, item.xpw * config.width, item.yph * config.height, item.wpw * config.width, item.hph * config.height);
}
}
context.save();
let canvasSrc = myCanvas.toDataURL("image/png");
if (callback && callback instanceof Function) {
callback(canvasSrc)
}
}
}, 50);
}
这一切都挺顺利得完成了,iOS基本上都可以识别上面的二维码信息,并且跳转到对应的公众号去,但是安卓却时好时不好,让人伤脑筋。
经过一个下午的调试,排除不可能的因素,一开始以为是二维码的位置关系,的确调整了位置,可以被扫出,但是跳转的链接不知道为何不正确,难倒是微信处理了?(此处有一个疑问)
于是,调试了另一种方案,直接放二维码链接,不经过canvas,很和谐得跳转到了我们想要其跳转的位置,排除了链接返回有问题的可能。
接下来,尝试得把canvas最后转为base64图片的格式修改为jpeg后,才发现,安卓机神奇得都可以跳转了。(这是经过一番周折的尝试结果,具体为何还没有结论)
以上内容,希望对遇到相同问题的同学给到帮助!