watermark.js
import Vue from "vue"; Vue.directive("watermark", (el, binding) => { (function (str, container, id, font) { setTimeout(function () { var containerWidth = container.offsetWidth || "400"; // 获取父容器宽 var containerHeight = container.offsetHeight || "100"; // 获取父容器高 container.style.position = "relative"; // 设置布局为相对布局 // 创建canvas元素(先制作一块背景图) const can = document.createElement("canvas"); can.width = containerWidth; // 设置每一块的宽度 can.height = containerHeight; // 高度 const cans = can.getContext("2d"); // 获取canvas画布 cans.rotate((-20 * Math.PI) / 270); // 逆时针旋转π/9 cans.font = font || "20px PingFang-SC-Regular"; // 设置字体 cans.fillStyle = "rgba(219,8,8, 0.3)"; // 设置字体的颜色 cans.textAlign = "left"; // 文本对齐方式 cans.textBaseline = "Middle"; // 文本基线 cans.fillText(str, 0, (4 * can.height) / 5); // 绘制文字 // 创建一个div元素 const div = document.createElement("div"); div.id = id; // 设置id div.style.pointerEvents = "none"; // 取消所有事件 div.style.top = "-15px"; div.style.left = "80px"; div.style.position = "absolute"; div.style.zIndex = "100000"; div.style.width = containerWidth + "px"; div.style.height = containerHeight + "px"; div.style.background = "url(" + can.toDataURL("image/png") + ") left top repeat"; container.appendChild(div); // 追加到页面 }, 300); })(binding.value.text, el, binding.value.id, binding.value.font); });
main.js
//水印 import "@/comm/js/directives/watermark";
home.vue
<template> <div class="contants" v-watermark="{ id: 'watermark', text: '水印文字1', font: '46px Microsoft JhengHei', }" > <div class="home_page"> ..... </div> </div> </template>