图片载入画布时会存在跨域问题,需要服务器那边把图片移动到相同的域名上或者启用 CORS
也可以让后台转成base64格式再输出到页面上

'use strict';
// 背景图片路径
var bgMap = '';

// 用户头像图片路径
var userMap = 'getAvatar()?>';

// 二维码图片路径
var codeMap = '';

// 用户名称
var userName = 'nickname?>';

// 创建画布
var canvasObj = document.createElement("canvas");
canvasObj.getContext("2d");
canvasObj.width = 750;
canvasObj.height = 1206;

// 初始化 2d画布上下文
var canvas2D = canvasObj.getContext("2d");

// 加载背景图片
var bgImg = new Image();
bgImg.crossOrigin = "Anonymous";
bgImg.src = drawObj.bgMap;
bgImg.onload = function() {

// 加载完成后 将背景图片载入画布
canvas2D.drawImage(bgImg, 0, 0, canvasObj.width, 1206);

// 填充画布内容 完成后执行回调 生成图片
draw(canvasObj, function() {

var imageUrl = canvasObj.toDataURL("image/jpeg", 1); // 图片格式, 图片质量 0 ~ 1

$('.J_loadMsg').style.display = 'none';
$('#image').src = imageUrl;
$('#image').style.display = 'block';
$('.tip-share').style.display = 'block';
});
};
function draw(elm, callback){

var canvas2D = elm.getContext("2d");

// 加载用户头像
var userImg = new Image();

userImg.crossOrigin = "Anonymous";
userImg.src = userMap;
userImg.onload = function(){

var l = elm.width / 2 - 90;
l = 0 > l ? 0 : l;

// 编辑文本样式
canvas2D.save();
canvas2D.arc(elm.width / 2 - 2, 239, 84, 0, 2 * Math.PI);
canvas2D.strokeStyle = "#ffffff";
canvas2D.lineWidth = 3;
canvas2D.stroke();
canvas2D.clip();
canvas2D.drawImage(userImg, l, 147, 180, 180);
canvas2D.restore();
canvas2D.textAlign = "center";
canvas2D.font = "36px";
canvas2D.fillStyle = "#2d2d2d";
canvas2D.fillText(userName, elm.width / 2, 385);

// 加载二维码图片
var codeImg = new Image();

codeImg.crossOrigin = "Anonymous";
codeImg.src = codeMap;
codeImg.onload = function(){

var ls = elm.width / 2 - 150;
ls = 0 > ls ? 0 : ls;

canvas2D.drawImage(codeImg, ls, 655, 300, 300);
canvas2D.restore();
callback();
};

};

}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Captcha Code