Vue下原生代码无依赖非常方便的给网页背景添加水印

2022-06-10 774点热度 0人点赞 0条评论

为了防止用户截屏后传播内容,需要给某些内容背景增加水印。本篇是介绍在Vue项目中增加水印,不添加第三方package,原声代码实现。

先上效果图:

干活实现方法

新增 directives.js

import Vue from 'vue'
 
Vue.directive('watermark',(el,binding)=>{
    function addWaterMarker(str,parentNode,font,textColor){// 水印文字,父元素,字体,文字颜色
        var can = document.createElement('canvas');
        parentNode.appendChild(can);
        can.width = 250;
        can.height = 200;
        can.style.display = 'none';
        var cans = can.getContext('2d');
        cans.rotate(-20 * Math.PI / 180);
        cans.font = font || "13px Microsoft JhengHei";
        cans.fillStyle = textColor || "rgba(180, 180, 180, 0.3)";
        cans.textAlign = 'center';
        cans.textBaseline = 'Middle';
        cans.fillText(str, can.width / 3, can.height / 2);
        parentNode.style.background = "#fff url(" + can.toDataURL("image/png") + ")";
    }
    addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor)
})

以上新增了watermark的directive,下面是如何在vue页面中使用:

<template>
    <div v-watermark="{text:watermark}">
        
    </div>
</template>

<script>
import  '@/assets/directives.js'
export default {
    data() {
        return {
            watermark: '水印内容水印内容'
        }
    },
    
    created() {
        
    },
    methods: {

    }
}
</script>

<style lang="less" scoped>

</style>

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论