朋友圈有些分享功能是通过长按图片另存来实现的,就像淘宝内部要分享朋友圈的时候一样,这些图片可以用canvas来合成。
获取了img的dom对象以后,进行base64的转。
//加载对象
$page.getArrl = function() { arrl = [{ type: "img", img: document.getElementById("bg"), x: 0, y: 0, 750, height: 1334 }, { type: "img", img: document.getElementById("blank"), x: 0, y: 0, 750, height: 26 }, { type: "img", img: document.getElementById("logo"), x: 28, y: 0, 214, height: 136 }, { type: "img", img: document.getElementById("mobi_cloud"), x: 0, y: 545, 746, height: 456 } ]; switch ($page.mobi) { case 1: arrl = arrl.concat([ { type: "img", img: document.getElementById("page2_img_1"), x: 0, y: 130, 750, height: 289 }, { type: "img", img: document.getElementById("page2_img_2"), x: 0, y: 418, 750, height: 84 }, { type: "img", img: document.getElementById("page2_img_3"), x: 0, y: 505, 750, height: 60 } ]); break; case 2: arrl = arrl.concat([{ type: "img", img: document.getElementById("page3_img_1"), x: 0, y: 150, 750, height: 414 }, { type: "img", img: document.getElementById("page3_img_2"), x: 255, y: 950, 224, height: 71 }, { type: "img", img: document.getElementById("page3_img_3"), x: 0, y: 1015, 750, height: 61 } ]); break; case 3: arrl = arrl.concat([{ type: "img", img: document.getElementById("page4_img_1"), x: 130, y: 133, 422, height: 470 }, { type: "img", img: document.getElementById("page4_img_2"), x: 575, y: 118, 174, height: 129 } ]); break; default: } if ($page.text === 3) { n = 909; } else { n = 879; } arrl = arrl.concat([ // { type: "img", img: document.getElementById("metoo_btn"), x: 168, y: 1200, 383, height: 88 }, { type: "img", img: document.getElementById("mobi_note_bg" + $page.text), x: 0, y: 562, 746, height: 456 }, { type: "text", text: $page.name, font: "24px 'Microsoft Yahei', Tahoma, Helvetica, Arial, sans-serif", style: "red", x: 330, y: n } ]); }
//执行合成 $page.getArrl(); $page.merge.img({ 750, height: 1334, material: arrl }, function(data) { $("#merged").attr("src", data); $(".share_btn").show(); }); //封装的方法 $page.merge = { img: function(obj, callback) { var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'); canvas.width = obj.width; canvas.height = obj.height; ctx.rect(0, 0, canvas.width, canvas.height); ctx.fill(); function drawing(n) { if (n < obj.material.length) { if (obj.material[n].type && obj.material[n].type == "text") { ctx.font = obj.material[n].font; ctx.fillStyle = obj.material[n].style || "#fff"; var textArr = obj.material[n].text.split(" "); for (var i = 0; i < textArr.length; i++) { ctx.fillText(textArr[i], obj.material[n].x, obj.material[n].y + (30 * i)); } } else { ctx.drawImage(obj.material[n].img, obj.material[n].x, obj.material[n].y, obj.material[n].width, obj.material[n].height); } drawing(n + 1); //递归 } else { //保存生成作品图片 if (callback) callback(canvas.toDataURL("image/jpeg", 0.6)); canvas = null; } } drawing(0); }, saveFile: function(data) { var dataImg = data.replace("image/jpeg", "image/octet-stream"); document.location.href = dataImg; } };