js文字水印

/**
 * Created by 晟途 on 2017/9/21.
 */
!function () {

  class Stamp {

    constructor(dom, text, options = {}) {

      let $root = document.getElementById(dom.replace('#',''));

      $root.style.position = "relative";

      let d = document.createElement('div');

      let style = {
        position: "fixed",
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        opacity: options.opacity ? options.opacity : .05,
        "pointer-events": "none",
        "z-index": 999999,
        "background-repeat":"repeat"
      };

      for(let key in style) d.style[key] = style[key];

      document.body.appendChild(d);

      let bgUrl = this.stamp(d, text);
      //低版本IE若是pointer-event失效須要hack
      !this.supportsPointerEvents() && this.bindClick($root,bgUrl,d);
    }

    bindClick ($root,bgUrl,removeTarget) {

      removeTarget.attachEvent('onclick', (e)=>{
        removeTarget.style.display = "none";
        let x = e.x, y = e.y;
        let target = document.elementFromPoint(x,y);
        let evt = document.createEvent('MouseEvents');
        evt.initEvent("click", true, true);
        target.dispatchEvent(evt);
        removeTarget.style.display = "block";
      })

    }

    supportsPointerEvents (){

      let dummy = document.createElement('_');

      if(!('pointerEvents' in dummy.style)) return false;

      dummy.style.pointerEvents = 'auto';
      dummy.style.pointerEvents = 'x';

      document.body.appendChild(dummy);

      let r = getComputedStyle(dummy).pointerEvents === 'auto';
      document.body.removeChild(dummy);

      return r;
    }

    stamp (dom, text) {
      var c = document.createElement("canvas");
      var ctx = c.getContext("2d");
      ctx.rotate(-20*Math.PI/180);
      ctx.font = "16px/20px arial";
      var gradient=ctx.createLinearGradient(0,0,c.width,0);
      gradient.addColorStop("0","magenta");
      gradient.addColorStop("0.5","blue");
      gradient.addColorStop("1.0","red");
      ctx.fillStyle=gradient;
      ctx.fillText(text,10,50);
      ctx.fillText(text,120,80);
      var bgUrl = convertCanvasToImage(c)
      dom.style.backgroundImage = 'url(' + bgUrl + ')';
      function convertCanvasToImage(canvas) {
          return canvas.toDataURL("image/png");
      }
      return bgUrl;
    }

    encode (input) {
      var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
      var output = "";
      var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
      var i = 0;

      input = this._utf8_encode(input);

      while (i < input.length) {

        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
          enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
          enc4 = 64;
        }

        output = output +
          _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
          _keyStr.charAt(enc3) + _keyStr.charAt(enc4);

      }

      return output;
    }

    _utf8_encode (string) {
      string = string.replace(/\r\n/g, "\n");
      var utftext = "";

      for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
          utftext += String.fromCharCode(c);
        }
        else if ((c > 127) && (c < 2048)) {
          utftext += String.fromCharCode((c >> 6) | 192);
          utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
          utftext += String.fromCharCode((c >> 12) | 224);
          utftext += String.fromCharCode(((c >> 6) & 63) | 128);
          utftext += String.fromCharCode((c & 63) | 128);
        }

      }

      return utftext;
    }

    setA (target, obj) {
      for(let key in obj) {
        target.setAttribute(key, obj[key])
      }
    }
  }
  window.__Stamp = Stamp
}()

上面是圖片背景是canvasjavascript

也能夠用svg生成:java

/**
 * Created by 晟途 on 2017/9/21.
 */
'use strict';

class Stamp {

  constructor(dom, text, options = {}) {

    let $root = document.getElementById(dom.replace('#',''));

    $root.style.position = "relative";

    let d = document.createElement('div');

    let style = {
      position: "fixed",
      left: 0,
      right: 0,
      top: 0,
      bottom: 0,
      opacity: options.opacity ? options.opacity : .05,
      "pointer-events": "none",
      "z-index": 999999,
      "background-repeat":"repeat"
    };

    for(let key in style) d.style[key] = style[key];

    document.body.appendChild(d);

    let bgUrl = this.stamp(d, text);
    //低版本IE若是pointer-event失效須要hack
    !this.supportsPointerEvents() && this.bindClick($root,bgUrl,d);
  }

  bindClick ($root,bgUrl,removeTarget) {

    removeTarget.attachEvent('onclick', (e)=>{
      removeTarget.style.display = "none";
      let x = e.x, y = e.y;
      let target = document.elementFromPoint(x,y);
      let evt = document.createEvent('MouseEvents');
      evt.initEvent("click", true, true);
      target.dispatchEvent(evt);
      removeTarget.style.display = "block";
    })

  }

  supportsPointerEvents (){

    let dummy = document.createElement('_');

    if(!('pointerEvents' in dummy.style)) return false;

    dummy.style.pointerEvents = 'auto';
    dummy.style.pointerEvents = 'x';

    document.body.appendChild(dummy);

    let r = getComputedStyle(dummy).pointerEvents === 'auto';
    document.body.removeChild(dummy);

    return r;
  }

  stamp (dom, text) {
    var _ns = "http://www.w3.org/2000/svg";
    // 建立一個svg對象
    var svg = document.createElementNS(_ns, "svg");
    var width = 250, height = 100;

    this.setA(svg, {
      width : width,
      height : height
    })

    // // svg中繪製文本
    var svgText = document.createElementNS(_ns, "text");

    this.setA(svgText, {
      fill: "black",
      "text-anchor": "middle",
      "font-family": "monospace",
      "transform": "translate(125, 50)rotate(-15)"
    })

    svgText.textContent = text

    svg.appendChild(svgText);

    var svgStr = new XMLSerializer().serializeToString(svg);

    var bgUrl = 'data:image/svg+xml;base64,' + this.encode(svgStr);

    dom.style.backgroundImage = 'url(' + bgUrl + ')';

    return bgUrl;
  }

  encode (input) {
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = this._utf8_encode(input);

    while (i < input.length) {

      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }

      output = output +
        _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
        _keyStr.charAt(enc3) + _keyStr.charAt(enc4);

    }

    return output;
  }

  _utf8_encode (string) {
    string = string.replace(/\r\n/g, "\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

      var c = string.charCodeAt(n);

      if (c < 128) {
        utftext += String.fromCharCode(c);
      }
      else if ((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      }
      else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }

    return utftext;
  }

  setA (target, obj) {
    for(let key in obj) {
      target.setAttribute(key, obj[key])
    }
  }
}

module.exports = Stamp;

export default Stamp;
相關文章
相關標籤/搜索