以下例子是在H5端顯示,web端亦同.
html結(jié)構(gòu) :
<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文檔點擊這里查看.
//我在這里就定義了一個繪制的函數(shù).
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 => { //作用將回調(diào)延遲到下次 DOM 更新循環(huán)之后執(zhí)行
this.img_src = c.toDataURL("image/jpeg", 1); //這就導出為 base64 格式.
});
}
*注意: 遇到drawImage畫板當中繪制圖片的時候,最好先新建一個image對象賦值,避免發(fā)生圖片不顯示等錯誤.
download(){
this.box_img = new Image();
this.box_img.setAttribute("crossOrigin", "anonymous");
this.box_img.src = "xxx";
}