helloluckworld

在vue项目中通过自定义指令,使用canvas特性生成base64格式的图片文件,并将其设置为背景图片,从而实现页面或组件局部水印效果

1、新建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 = 400;
        can.height = 200;
        can.style.display = \'none\';
        var cans = can.getContext(\'2d\');
        cans.rotate(-20 * Math.PI / 180);
        cans.font = font || "16px Microsoft JhengHei";
        cans.fillStyle = textColor || "rgba(180, 180, 180, 0.3)";
        cans.textAlign = \'left\';
        cans.textBaseline = \'Middle\';
        cans.fillText(str, can.width / 3, can.height / 2);
        parentNode.style.backgroundImage = "url(" + can.toDataURL("image/png") + ")";
    }
    addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor)
})

  2、min.js 引入directives.js (我的directives.js文件在utils目录下)

import  \'@/utils/directives\'

3、调用指令

  如果希望在整个项目中都添加水印,可以在app.vue中使用指令

  

<template>
  <div id="app">
    <router-view v-watermark="{text:\'水印名称\',textColor:\'rgba(180, 180, 180, 0.3)\'}" />
  </div>
</template>

  如果希望只给某个组件添加水印,可以直接在组件html中调用指令

  

分类:

技术点:

相关文章:

  • 2021-04-20
  • 2021-05-29
  • 2021-09-09
  • 2021-11-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案