JavaScript实践(一)页面添加水印

<script>
(function() {
  var name = ${this.name};
  var opacity = ${this.opacity};
  var genWater = function(name) {
    var waterCanvas = document.createElement('canvas');
    waterCanvas.id = 'water-canvas';
    waterCanvas.setAttribute('width', name.length * 12);
    waterCanvas.setAttribute('height', 80);
    var ctx = waterCanvas.getContext('2d');
    ctx.rotate(Math.PI / 180 * 30);
    ctx.font = '15px serif';
    ctx.fillText(name, 10, 10);
    var base64Url = waterCanvas.toDataURL();

    var waterMarkDiv = document.createElement('div');
    var styleStr = 'position:absolute;top:0;left:0;width:100%;height:100%;z-index:99999;pointer-events:none;background-image:url(' + base64Url + ');opacity: ' + opacity + ';';
    waterMarkDiv.setAttribute('style', styleStr);
    waterMarkDiv.classList.add('__wm');
    return waterMarkDiv;
  };
  var container = document.body;
  var waterMarkDiv = genWater(name);

  container.insertBefore(waterMarkDiv, container.firstChild);

  var callback = function(record, mutation) {
    for (var i = 0; i < record.length; i++) {
      var item = record[i];
      var target = item.target;
      if (target.nodeType === 1) {
        var removedNodes = item.removedNodes;
        if (target.nodeName === 'BODY' && removedNodes.length > 0) {
          for (var j = 0; j < removedNodes.length; j++) {
            var element = removedNodes[j];
            if (element.nodeType === 1 && element.nodeName === 'DIV' && element.classList.contains('__wm')) {
              waterMarkDiv = genWater(name);
              container.insertBefore(waterMarkDiv, container.firstChild);
            };
          };
        };
        var type = item.type;
        if (target.nodeName === 'DIV' && target.classList.contains('__wm') && type === 'attributes') {
          container.removeChild(waterMarkDiv);
        };
      };
    };
  };

  if (typeof MutationObserver === 'function') {
    var obs = new MutationObserver(callback);
    var options = {
      childList: true,
      attributes: true,
      subtree: true,
      characterData: true
    };
    obs.observe(container, options);
  };
})();
</script>

 

posted @ 2019-05-15 19:48  zhoulixue  阅读(1433)  评论(0编辑  收藏  举报