web前端

HTML添加水印

/**
 * 显示/创建水印
 * @param options
 * @param container 父级容器
 * @param text 水印文字
 * @param width 宽度
 * @param height 高度
 * @param zIndex 显示层级
 * @param margin 行间距
 * @param fontSize 字体大小
 * @param color 字体颜色
 * @param opacity 透明度
 * @param rotate 旋转角度
 * @param show 默认是否显示
 */
function createWatermark(options = {}) {
  const {
    container = el = '#app',
    text = '',
    width = 300,
    height = 200,
    zIndex = 9999,
    margin = 10,
    fontSize = 18,
    color = '#bbb',
    opacity = 0.5,
    rotate = -30,
    show = true
  } = options

  if (document.querySelector('.watermark')) {
    document.querySelector('.watermark').style.display = 'block'
    return
  }

  const cas = document.createElement('canvas')
  cas.setAttribute('width', width)
  cas.setAttribute('height', height)
  cas.style.border = '1px solid #000'

  const ctx = cas.getContext('2d')
  ctx.font = `${fontSize}px sans-serif`
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  ctx.fillStyle = color
  ctx.translate(width / 2, height / 2)
  ctx.rotate((rotate * Math.PI) / 180)
  ctx.translate(0, 0)

  // 计算宽度
  const charts = text.split('')
  let firstLine = ''
  let secondLine = ''
  for (let index = 0; index < charts.length; index++) {
    if (ctx.measureText(firstLine).width < width - fontSize * 3) {
      firstLine += charts[index]
    } else {
      secondLine += charts[index]
    }
  }
  const showSecond = secondLine.length > 0
  console.log(firstLine)
  ctx.fillText(firstLine, 0, showSecond ? -fontSize - margin / 2 : 0)
  showSecond && ctx.fillText(secondLine, 0, margin + fontSize)
  const imageBase64 = cas.toDataURL()
  const watermarkEl = document.createElement('div')
  const containerEl = document.querySelector(container)
  containerEl.style.position = containerEl.style.position ? containerEl.style.position : 'relative'
  watermarkEl.className = 'watermark'
  watermarkEl.setAttribute(
    'style',
    `
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: ${zIndex};
    display: ${show ? 'block' : 'none'};
    width: 100%;
    height: 100%;
    background: url(${imageBase64}) repeat;
    opacity: ${opacity};
    pointer-events:none;
  `
  )
  document.querySelector(container).appendChild(watermarkEl)
}

/**
 * 隐藏水印
 */
function hideWatermark() {
  if (document.querySelector('.watermark')) {
    document.querySelector('.watermark').style.display = 'none'
  }
}

/**
 * 移除水印
 */
function removeWatermark() {
  document.querySelector('.watermark') && document.querySelector('.watermark').remove()
}

export default {
  createWatermark,
  removeWatermark,
  hideWatermark
}

发表评论

电子邮件地址不会被公开。