HTML:
<canvas id="myCanvas" width="640" height="1008" style="display:none">
<!-- 圆形头像嵌套canvas -->
<canvas id="cCanvas" style="display:none"></canvas>
// canvas画海报
var loading;
function imageToCanvas() {
if(activity_exist()) {
turnguanzhu();
return;
}
// if($("#c_class").val()==0){
// layer.open({
// content: "请选择生成证书的课程",
// btn: '确定'
// });
// $('#popup_reg').popup();
// return;
// }
loading = layer.open({
shadeClose:false,
type:2,
content:'正在生成海报'
});
var canvas =document.getElementById("myCanvas");
var element =poster_item[poster_id]['c_data'];
var ctx = canvas.getContext("2d");
var image_arr = {};
var text_arr = {};
for(var iin element) {
if(['bg','roundhead','qr'].indexOf(i) > -1) {
image_arr[i]=element[i];
if(i=='roundhead'){
element[i]['src'] =$('.make-poster .wx_photo').attr('src');
}
}else if(['c_class','realname','mobile','c_date'].indexOf(i) > -1) {
text_arr[i]=element[i];
if(i=='c_class' || i=='c_date'){
element[i]['value'] =$('.make-poster .'+i).html();
}else{
element[i]['value'] =$('.make-poster .wx_'+i).html();
}
}
}
drawImage(ctx,image_arr,text_arr);
}
function drawImage(ctx,image_arr,text_arr) {
var rank = ['bg','roundhead','qr'];
draw(0,image_arr[rank[0]]);
function draw(i,item) {
if(i <= rank.length) {
i++;
if(item&&item.src) {
var image =new Image();
image.setAttribute('crossOrigin','anonymous');
image.src = item.src;
image.onload =function() {
if(rank[i-1]=='roundhead'){
var canvasTemp =document.getElementById("cCanvas");
canvasTemp.width =640;
canvasTemp.height =1008;
var contextTemp = canvasTemp.getContext('2d');
contextTemp.drawImage(image,item.left,item.top,item.width,item.height);
var ptn = ctx.createPattern(canvasTemp,'no-repeat');
let min =Math.min(item.width/2, item.height/2);
let r = min;
ctx.fillStyle = ptn;
ctx.arc(item.left+r, item.top+r, r, 0, Math.PI *2);
ctx.fill();
}else{
ctx.drawImage(image,item.left,item.top,item.width,item.height);
}
draw(i,image_arr[rank[i]]);
}
}else {
draw(i,image_arr[rank[i]]);
}
}else {
drawText(ctx,text_arr);
}
}
}
function drawText(ctx,text_arr) {
console.log(text_arr);
for(var iin text_arr) {
var item = text_arr[i];
if(item.value) {
ctx.textBaseline ='top';
ctx.textAlign = item.align;
ctx.font = item.size+"px Arial";
ctx.fillStyle = item.color;
if(item.align=='right'){
item.left = item.left+item.width;
}else if(item.align=="center"){
item.left =320;
}
ctx.fillText(item.value,item.left,item.top+item.size*0.5);
}
}
convertCanvasToImage()
}
// 转成图片
function convertCanvasToImage() {
var base64ImgSrc =document.getElementById("myCanvas").toDataURL("image/png");
submitForm(base64ImgSrc);
}
网友评论