要在 Vue.js 裡面寫 Canvas 的話,設置方面可以先參考我上一篇。
要建立浮水印的話,我是簡單地利用區塊重疊,把 canvas 壓在圖片上。
<div class="position-relative pic-block">
<canvas width="200" height="250" ref="canvas" class="position-absolute canvas"></canvas>
</div>
注意 canvas 的大小一定要透過 width 跟 height 設定,不然裡面的東西會變形。
在弄一個輸入欄位,用來抓取內容的。
<input v-model="watermark" type="text" class="form-control">
接著在 data 設立這些變數,我本來是要做可以調整浮水印樣式的,不過這邊就放簡單的單一種樣子。
data() {
return {
vueCanvas: null,
x:5,
y:20,
canvasHeight: 250,
canvasWidth: 200,
watermark: "",
textAlign: "left"
}
}
mounted 的時候一樣更新物件
mounted(){
var canvas = this.$refs.canvas.getContext("2d");
this.vueCanvas=canvas;
}
接著寫一個 methods,在更新 watermark 的時候也會更新 canvas
updateCanvas(){
this.vueCanvas.clearRect(0,0,this.canvasWidth,this.canvasHeight);
this.vueCanvas.font = "20px arial";
this.vueCanvas.textAlign = this.textAlign;
this.vueCanvas.translate( canvas.width / 2, canvas.height / 2 );
this.vueCanvas.strokeStyle = "black";
this.vueCanvas.strokeText(this.watermark,this.x,this.y);
}
watch 變數
watch:{
watermark(value){
this.updateCanvas();
}
}