美文网首页
给背景加水印

给背景加水印

作者: ThemisHoo | 来源:发表于2019-05-30 15:20 被阅读0次
    // 配置水印的字体大小,行数,列数等参数,可改为可配置参数
    let watermark = {
        id: 'watermark',
        fontSize: '16px',
        rowNum: 3,
        colNum: 6,
        rotate: 25,
        opacity: 0.1
      };
      let setWatermark = (str) => {
        let id = watermark.id;
        if (document.getElementById(id) !== null) {
          document.body.removeChild(document.getElementById(id))
        }
      
        let can = document.createElement('canvas');
        let clientWidth = window.innerWidth || document.documentElement.clientWidth;
        let clientHeight = window.innerHeight || document.documentElement.clientHeight;
        can.width = clientWidth / watermark.rowNum;
        can.height = clientHeight / watermark.colNum;
      
        let cans = can.getContext('2d');
        cans.rotate(-watermark.rotate * Math.PI / 180);
        cans.font = `${watermark.fontSize} Vedana`;
        cans.fillStyle = `rgba(0, 0, 0, ${watermark.opacity})`;
        cans.textAlign = 'left';
        cans.textBaseline = 'Middle';
        cans.fillText(str, 0, can.height);
        let div = document.createElement('div');
        div.id = id;
        div.style.cssText = `
            pointer-events:none;
            top:0;
            left:0;
            position:fixed;
            z-index:500;
            width:${clientWidth}px;
            height:${clientHeight}px;
            background:url( ${can.toDataURL('image/png')}) left top repeat
        `;
        document.body.appendChild(div); // 这里将水印加在了body上
        return id
      };
      // 该方法只允许调用一次
      watermark.setText = (str) => {
        setWatermark(str);
        window.onresize = () => {
          setWatermark(str)
        }
      };
      watermark.remove = () => {
        let id = watermark.id;
        if (document.getElementById(id) !== null) {
          document.body.removeChild(document.getElementById(id))
        }
      };
      watermark.setOptions = (opts) => {
        if (!isJson(JSON.stringify(opts))) return;
        for (let k in opts) {
          watermark[k] = opts[k]
        }
      };
      
      function isJson(str) {
        if (typeof str === 'string') {
          try {
            let obj = JSON.parse(str);
            return !!(obj && typeof obj === 'object');
          } catch (e) {
            console.log('error:' + str + '!!!' + e);
            return false;
          }
        }
      }
      
      export default watermark
    
    import {  Watermark } from './watermark.js';
    
    let canvasImg = Watermark.setText(`水印文字`)
    document.getElementById('root').style.background = canvasImg
    

    相关文章

      网友评论

          本文标题:给背景加水印

          本文链接:https://www.haomeiwen.com/subject/hxlvtctx.html