如何给页面元素添加水印背景,在vue中怎么处理?

您的三连支持是我创作的动力!
这里写一个简单的给页面元素添加水印背景的方法,主要是添加文字行的。
在这里插入图片描述

步骤1:在canvas中画出这个水印

这里我写的注释很详细了,不会的可以看看canvas的相关api。

/**
 *  给一个页面元素添加水印背景
 * @param text 文字内容
 * @param textColor 文字颜色
 * @param backgroundColor 背景色
 * @param sourceBody 挂载元素
 */
function setWatermark({
     
     text, textColor, backgroundColor}, sourceBody) {
    
    
    let can = document.createElement('canvas')
    can.width = 150
    can.height = 120

    let cans = can.getContext('2d')
    cans.rotate(-20 * Math.PI / 180)
    cans.font = '15px Vedana'

    cans.fillStyle = textColor
    cans.textAlign = 'left'
    cans.textBaseline = 'Middle'
    cans.fillText(text, can.width / 20, can.height)
    sourceBody.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
    sourceBody.style.backgroundColor = backgroundColor
}


export default setWatermark

步骤2:注册自定义指令

  1. 如果是在普通的项目里,直接调用上面的方法就可以实现简单的水印背景效果了。
  2. 这里重点说一下在vue中,使用自定义指令的方式:
    为什么使用自定义指令?主要因为自定义指令里面带有el这个页面元素参数,所以说自定义指令主要就是用来干这个活儿的。
        app.directive('w-watermark', (el, binding) => {
    
    
            watermark({
    
    
                text:binding.value.label,
                textColor:"rgba(219,219,219,0.41)",
                backgroundColor:"#F5F6F7",
            },el)
        })

步骤3:应用自定义指令

自行改造,传入更多的参数,或者改变传入参数的方式都行!

  <div class="ork-body" v-w-watermark="{label:'12321321'}">
    <router-view></router-view>
  </div>

您的三连支持是我创作的动力!

猜你喜欢

转载自blog.csdn.net/qq_32594913/article/details/125554854
今日推荐