In the vUE project, through the custom instruction, the canvas feature is used to generate base64 format picture files, create div and set it as the background picture, and then locate to the place where you want to add watermark (or directly set the background picture), so as to achieve the local watermarking effect of pages or components.
- Create warterMark. Js
import Vue from 'vue' Vue.directive('watermark', (el, binding)=>{ function addWaterMarker(str, parentNode, font, TextColor){// watermark text, parent element, font, textColor let can = document.createelement ('canvas'); parentNode.appendChild(can); can.width = 200; can.height = 140; can.style.display = 'none'; let cans = can.getContext('2d'); let img = new Image(); img.src = require('.. /.. /assets/images/waterMarkLogo.png'); img.onload = () => { console.log(img) cans.drawImage(img, 10, 0, 115, 70); cans.rotate(-27 * Math.PI / 180); cans.font = font || "10px Microsoft Yahei"; cans.fillStyle = textColor || "#707070"; cans.textAlign = 'left'; cans.fillText(str, -10, 108); cans.stroke(); / / set the background picture / / parentNode. The style.css. BackgroundImage = "url (" + can. ToDataURL (" image/PNG") + ") "; let div = document.createElement('div'); div.id = str; div.style.pointerEvents = 'none'; div.style.top = '0'; div.style.left = '0'; div.style.position = 'absolute'; div.style.zIndex = '100000'; div.style.width = '100%'; div.style.height = '100%'; div.style.background = 'url(' + can.toDataURL('image/png') + ')'; parentNode.appendChild(div); } } addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor) })Copy the code
- Main.js imports wartermark.js (or in a page you want to add)
My wartermark. js file is in the directive directory
import '@/directive/warterMark.js'
Copy the code
- Call instruction
If you want to add watermarks throughout your project, you can use instructions in app.vue
<template> <div id="app"> <router-view v-watermark="{text: 'watermark ', textColor: 'rgba (180, 180, 180, 0.3)'} "/ > < / div > < / template >Copy the code