ページの背景ウォータマークを描画します.

2145 ワード

function Watermark (data) {
  this.id = data.id || 'my-canvas'; // canvas id
  this.wrapper = document.querySelector(data.wrapper) || document.body; //     
  this.attribute = data.attribute; // canvas  
  this.fillStyle = data.fillStyle || '#dddddd'; //        
  this.font = data.font || '10px sans-serif'; //       
  this.text = data.text || '    '; //     
  this.rotate = data.rotate || -20; //     
  this.init(data);
}

//   canvas
Watermark.prototype.creatCanvas = function () {
  const _is = document.querySelector(`#${this.id}`);
  if (!_is) {
    const _canvas = document.createElement('canvas');
    const { width, height } = this.attribute;
    _canvas.id = this.id;
    _canvas.width = width;
    _canvas.height = height;
    for (const attr in this.attribute) {
      _canvas.style[attr] = this.attribute[attr];
    }
    this.wrapper.appendChild(_canvas);
    return _canvas;
  }
  return _is;
}

//   canvas   
Watermark.prototype.clearCanvas = function () {
  this.wrapper.removeChild(this.creatCanvas());
  this.wrapper.style.backgroundImage = 'none';
  this.wrapper.style.userSelect = 'text';
}

//    canvas
Watermark.prototype.init = function () {
  this.creatCanvas();
  this.drawWatermark();
}

//     
Watermark.prototype.drawWatermark = function () {
  const _canvas = this.creatCanvas();
  const context = _canvas.getContext("2d");
  context.fillStyle = this.fillStyle;
  context.font = this.font;
  context.rotate(this.rotate * Math.PI / 180);
  this.text.split(',').map((e, i) => {
    context.fillText(e, 70 * i, 50);
    context.save();
  })
  this.wrapper.style.userSelect = 'none';
  this.wrapper.style.backgroundImage = `url(${_canvas.toDataURL()})`;
  return context;
}

export default Watermark;

使用
      watermark = new Watermark({
        attribute: {
          width: 120,
          height: 50,
          display: 'none'
        },
        wrapper: '.iphone_module',
        fillStyle: '#ddd',
        font: '14px microsoft yahei',
      });