vue 水印插件
插件:
directives.js
import Vue from 'vue' /** * author: zuokun * 水印 * text:水印文字 * font:字体 * textColor:文字颜色 * width:宽度 * height:高度 * textRotate:偏转度 -90到0, 负数值,不包含-90 */ Vue.directive('watermark',(el,binding)=>{ let text = binding.value.text; let font = binding.value.font || "16px Microsoft JhengHei"; let textColor = binding.value.textColor || "rgba(215, 215, 215, 0.2)"; let width = binding.value.width || 400; let height = binding.value.height || 200; let textRotate = binding.value.textRotate||-20; function addWaterMarker(parentNode){ var can = document.createElement('canvas'); parentNode.appendChild(can); can.width = width; can.height = height; can.style.display = 'none'; var cans = can.getContext('2d'); cans.rotate(textRotate * Math.PI / 180); cans.font = font; cans.fillStyle = textColor ; cans.textAlign = 'left'; cans.textBaseline = 'Middle'; cans.fillText(text, 0, can.height); parentNode.style.backgroundImage = "url(" + can.toDataURL("image/png") + ")"; } addWaterMarker(el) })
使用:
1.引入:
import '@/utils/directives.js';
2.设置配置:
watermarkConfig:{//水印
text:'测试水印',
font:'20px 微软雅黑',
textColor:'#bcbcbc',
width : 150, //水印文字的水平间距
height : 100, //水印文字的高度间距(低于文字高度会被替代)
extRotate : -30 //-90到0, 负数值,不包含-90
},
3.页面使用:
<div v-watermark="watermarkConfig"> </div>
效果:
页面完整代码:
<template> <div id="test"> <div class="bodydiv" v-watermark="watermarkConfig"> </div> </div> </template> <script> import Vue from 'vue'; import '@/utils/directives.js'; export default { data() { return { watermarkConfig:{//水印 text:'测试水印', font:'20px 微软雅黑', textColor:'#bcbcbc', width : 150, //水印文字的水平间距 height : 100, //水印文字的高度间距(低于文字高度会被替代) extRotate : -30 //-90到0, 负数值,不包含-90 }, } }, methods: { }, created() { //初始化加载 }, mounted() { //加载完成回调 }, } </script> <style> #test .bodydiv { width: 100%; height:1000px; } </style>
结束