划词标注2-使用花括号概括信息

实现交互

在【划词标注1】的博文中,实现了如何给文字加入底色,本篇主要描述如何使用花括号概括信息:

如图,就是如何给一段文本在上面或者下面绘制花括号并标注信息

实现思路

看起来简单,实现的过程中有很多细节需要处理:比如位置信息的获取,重叠位置的处理,临界情况的处理等,这里不再细述,仅仅描述重要图形的绘制方法

  • 选中文本后,获取文本的位置信息,在文字的上方绘制矩形;

let rectConcation = mg
        .rect(rw, rh) // rw,rh 绘制矩形的宽高
        .move(
          rx,
          type === "top" ? ry - this.wordHeight : ry + this.wordHeight + 6
        ) // 矩形的位置,type==='top'表示在上方绘制 rx,ry位置信息
        .fill(type === "top" ? this.wordColors.top: this.wordColors.bottom) // 颜色
        .data("text", text) //信息记录
        .data("id", id)
        .data("index", index)
  • 在矩形中绘制文字;
// 文字
      mg.plain(text)
        .attr("x", rx + text.length + 1)
        .attr(
          "y",
          type === "top"
            ? ry - this.wordHeight / 2 + 1
            : ry + this.wordHeight + 15
        )
        .fill("black")
        .font({ size: 11 })
  • 在矩形下绘制花括号;
// path(这里是重点)
      let path;
      // 参数说明:x,ry表示括号的起始点
      // width 描述文字的宽度 wordHeight文字的高度(是固定的,所以用固定变量表示的)
      if (type === "top") { 
        path =
          `M${x},${ry} ` + 
          `Q${x},${ry - 4} ${x + width / 4},${ry - 2} T${x + width / 2},${ry -
          4}` +
          `M${x + width / 2},${ry - 4} ` +
          `Q${x + width / 2},${ry} ${x + (width * 3) / 4},${ry - 2} T${x +
          width},${ry}`;
      } else {
        path =
          `M${x},${ry + this.wordHeight} ` +
          `Q${x},${ry + this.wordHeight + 4} ${x + width / 4},${ry +
          this.wordHeight +
          2} T${x + width / 2},${ry + this.wordHeight + 4}` +
          `M${x + width / 2},${ry + this.wordHeight + 4} ` +
          `Q${x + width / 2},${ry + this.wordHeight} ${x +
          (width * 3) / 4},${ry + this.wordHeight + 2} T${x + width},${ry +
          this.wordHeight}`;
      }
      mg.path(path)
        .stroke("#002998")
        .fill("none")
        .attr("class", "curly")
        .attr("data-id", id);

这里要注意的是花括号根据文本对称显示,矩形的中心对准文本的中心

重叠情况下的样式如下:

猜你喜欢

转载自www.cnblogs.com/webhmy/p/12079406.html