l-watermark icon indicating copy to clipboard operation
l-watermark copied to clipboard

大佬,想问下,如果水印是多行的,那么要求除了第一行之外的每一行都要跟第一行文字左对齐,你在这代码要怎么改?

Open nicky132 opened this issue 10 months ago • 0 comments

image 我的写法貌似有问题: image.ts文件中修改代码 ` _fillText2Ctx( ctx: CanvasRenderingContext2D, textConfig: ImageConfig.Text, width: number, height: number ) { let { position, color, fontSize, cSpace, vSpace, angle, text, linesSpace } = textConfig ctx.font = `${fontSize}px microsoft yahei` ctx.fillStyle = color const lines = text?.split('\n') let longestString = lines.reduce(function (longest, current) { return longest.length > current.length ? longest : current }, '') ctx.textAlign = 'center' ctx.textBaseline = 'middle' const { width: textWith } = getTextSize(longestString, fontSize) const wmWidth = textWith + cSpace const wmHeight = textWith + vSpace ctx.translate(width / 2, height / 2) ctx.rotate((Math.PI / 180) * angle)

    const diagonal = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2))

    let w = -diagonal / 2
    let h = -diagonal / 2
    let firstLineWidth = 0 // 用于保存第一行文本的宽度
    let y = 0
    if (lines.length > 1) {
      let w = -diagonal / 2
      let h = -diagonal / 2
      while (h < diagonal / 2) {
        while (w < diagonal / 2) {
          for (let i = 0; i < lines.length; i++) {
            console.log(
              lines,
              w - lines[0].length,
              w,
              h,
              lines[1].length,
              wmWidth,
              wmHeight,
              linesSpace / 2,
              fontSize,
              textWith,
              lines[0].length,
              lines[1].length
            )
            ctx.fillText(lines[i], 0, (linesSpace + fontSize) * i)
            y = linesSpace ? fontSize + linesSpace / 2 : fontSize // 增加linesSpace像素的间距
          }
          w += wmWidth
        }
        w = -diagonal / 2
        h += wmHeight
      }
    } else {
      while (h < diagonal / 2) {
        while (w < diagonal / 2) {
          ctx.save() // 保存当前绘图状态
          ctx.fillText(text, w, h)
          ctx.restore() // 恢复之前的绘图状态
          w += wmWidth
        }
        w = -diagonal / 2
        h += wmHeight
      }
    }`

WaterMark.image({ target: document.getElementById('demo-image'), text: '张三xs二你好 8888\n220412', color: 'rgba(0, 0, 0, 0.2)', fontSize: 14, linesSpace: 8, })

貌似不行,因为1、第二行并没有跟第一行对齐;2、水印没有铺满整个容器

nicky132 avatar Apr 01 '24 15:04 nicky132