以下例子是在H5端显示,web端亦同.
html结构 :
<template>
<div class="canvasWrap">
/* 将其位置移出屏幕有效显示处,能够让img标签特殊操作. */
<canvas style="position: absolute;top:-1000px;" id="cjdCanvas"></canvas>
<img :src="img_src" class="img" />
</div>
</template>
css样式 :
<style>
html,body {
background-color: #ccc;
}
.canvasWrap {
width: 100%;
height: 100%;
position: relative;
display: flex;
align-items: center;
justify-content: center;
}
.canvasWrap .img {
width: 7.5rem;
height: 13.34rem;
}
</style>
具体的canvas文档点击这里查看.
//我在这里就定义了一个绘制的函数.
systemInfo() {
const rem = this.getViewportSize().width / 375 / 2; //获取手机屏幕大小 / 375的比值
this.rem = rem;
},
startDraw() {
const c = document.getElementById("cjdCanvas"), //找到该画板的 id
ctx = c.getContext("2d"),
rem = this.rem; //这个是因需要不同屏幕的适配,定义方法在上方
//绘制开始
c.width = 750 * rem;
c.height = 1334 * rem;
// console.log(logo_img)
ctx.drawImage(this.bg_img, 0 * rem, 0 * rem, 750 * rem, 1334 * rem);
ctx.font = 48 * rem + "px Arial";
ctx.fillStyle = "#FFFFFF";
ctx.fillText(card.name + "的成绩单", 38 * rem, 140 * rem);
...
ctx.drawImage(this.logo_img, 505 * rem, 26 * rem, 190 * rem, 50 * rem);
...
ctx.textAlign = "center";
ctx.font = 40 * rem + "px Arial";
ctx.fillStyle = "#fecd03";
...
ctx.fillText(card.diff_des, 146 * rem, 861 * rem);
//保存绘制
ctx.save();
this.$nextTick(e => { //作用将回调延迟到下次 DOM 更新循环之后执行
this.img_src = c.toDataURL("image/jpeg", 1); //这就导出为 base64 格式.
});
}
*注意: 遇到drawImage画板当中绘制图片的时候,最好先新建一个image对象赋值,避免发生图片不显示等错误.
download(){
this.box_img = new Image();
this.box_img.setAttribute("crossOrigin", "anonymous");
this.box_img.src = "xxx";
}