<template>
<div class="canvas">
<canvas id="img"></canvas>
</div>
</template>
<script>
export default {
name: 'home',
data() {
return {
imgUrl: require("../assets/people.png")
}
},
mounted() {
this.setWatermark('img', this.imgUrl, '圖片水印' )
},
methods: {
setWatermark(id, imgUrl, str) {
var canvasImg = document.querySelector(`#${id}`);
var ctxImg = canvasImg.getContext("2d");
var img = new Image();
img.src =imgUrl;
img.width = 150
img.height = 200
canvasImg.width = img.width
canvasImg.height = img.height
img.onload = function(){
ctxImg.drawImage(img, 0, 0, img.width, img.height);
// 創(chuàng)建水印canvas
var canvas = document.createElement('canvas');
canvas.id = "canvas"
// 設(shè)置canvas畫布大小
canvas.width = 80
canvas.height = 30
var ctx = canvas.getContext('2d')
ctx.rotate(6.10); // 水印旋轉(zhuǎn)角度
// ctx.translate(0, 0);
ctx.font = '14px Arial'
ctx.fillStyle = 'red'
ctx.fillText(str, 0, 20) // 水印在畫布的位置x,y軸
// ctx.strokeRect(0,0,canvas.width,canvas.height);
var tamp_w = Math.ceil(canvasImg.width / canvas.width)
var tamp_h = Math.ceil(canvasImg.height / canvas.height)+2
for(var i = 0; i < tamp_h; i++) {
for(var j = 0; j < tamp_w; j++) {
canvasImg.getContext("2d").drawImage(canvas, j * canvas.width, i* canvas.height)
}
}
}
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.canvas{
position: relative;
width: 800px;
height: 600px;
background-color: powderblue;
}
</style>
people.PNG