使用canvas生成图片,并含有水印
在项目中有一个功能是将获得的数据以PDF的方式展示,并且有水印
生成水印
这里使用自定义指令来实现操作
生成watermark.js来设置这个自定义指令
import Vue from 'vue'
Vue.directive('watermark', (el, binding) => {
function addWaterMarker(str, parentNode, font, textColor) { // 水印文字,父元素,字体,文字颜色
var can = document.createElement('canvas') //创建画布
parentNode.appendChild(can) // 将画布添加到传入进来的DOM元素中
can.width = 180 // 给画布设置宽高
can.height = 140
can.style.display = 'none' // 将背景图的画布隐藏不显示
var cans = can.getContext('2d') // 开始绘制画布
cans.rotate(-10 * Math.PI / 180) // 设置画布旋转角度
cans.font = font || '16px Microsoft JhengHei' // 画布的内容
cans.fillStyle = textColor || 'rgba(180, 180, 180, 0.3)' // 画布文字颜色
cans.textAlign = 'left'
cans.textBaseline = 'Middle'
cans.fillText(str, can.width / 5, can.height / 2) // 在画布上绘制填色的文字
parentNode.style.background = 'url(' + can.toDataURL('image/png') + ') repeat ' // 设置画布背景颜,这里的背景是将画布转化成64进制的路径
}
addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor)
})
<div id="pdfDom" ref="pdfDom" class="pdf-content" style="padding: 10px;">
<!-- <pdf-view :src="src" :if-page="true" /> -->
<van-cell v-for="(item,index) in pdfData" :key="index" v-watermark="{text:'明日教育',textColor:'rgba(180, 180, 180, 0.5)',font:'30px Microsoft JhengHei'}" size="large">
<div v-if="paperId === 4" class="isPC">
{{ item.title }}
<p>
{{ item.content }}
</p>
</div>
<div v-if="paperId === 2">
<p>
{{ item.type }}
</p>
<p v-for="item2 in item.context" :key="item2.index">
{{ item2.title }}: <br>
{{ item2.content }}
</p>
</div>
</van-cell>
</div>
生成图片
generateImg() {
const _this = this
html2Canvas(this.$refs['pdfDom'], {
allowTaint: true,
scale: 2,
dpi: 182,
backgroundColor: null,
useCORS: true,
width: this.$refs['pdfDom'].offsetWidth,
height: this.$refs['pdfDom'].offsetHeight
}).then(function(canvas) {
const dataURL = canvas.toDataURL('image/png')
_this.imgUrl = dataURL
}
)
}