绘制页面背景水印

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',
      });
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页