使用鼠标绘制canvas绘制多边形

实现一个鼠标绘制多边形,区域的功能,可以添加文字展示,并且支持文字换行,居中展示

效果如下请添加图片描述
实现主要思路:
绘制方面:要创建两个绘制的方法,第一个:绘制所有的图形通过allPoints进行存储,不报行正在绘制的点位列表
第二个:绘制当前正在画的点位列表并且,通过currentPoints进行存储
监听事件:监听鼠标的事件:移动,单击(绘制),双击(结束绘制)
文字位置计算:计算几何图形的中心点,计算换行的高度,计算最宽的文字宽度,通过计算得出中心点,再通过每段文字的宽度与最大文字宽度对比,小于最大宽度进行空格补齐实现居中显示
区域选中:通过计算点击位置是否再图形内循环计算
此外根据已经实现的函数,可以轻易的拓展功能,例如绘制矩形 圆形

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <style>
      img {
        user-select: none;
      }
    </style>
    <script src="./canvas.js"></script>
  </head>
  <body>
    <div id="app">
      <img
        width="1014"
        height="609"
        src="./地图.png"
        style="position: relative;opacity: 0;"
      />
      <canvas
        ref="canvas"
        style="position: absolute; top: 0; left: 0; z-index: 1"
      ></canvas>
      <div>
        <button @click="makeArea">绘制区域</button>
        <button @click="cancelMakeArea">取消绘制</button>
        <button @click="selectAreaHandler">选择区域</button>
        <button @click="openBounding">显示边框区域</button>
        <button @click="closeBounding">关闭边框区域</button>
        <button :disabled="!currentArea" @click="deleteArea">
          删除所选区域
        </button>
      </div>
      <div v-if="currentArea">已经选中:{{currentArea}}</div>
    </div>
    <script>
      const app = new Vue({
        el: "#app",
        data() {
          return {
            canvas: null,
            ctx: null,
            startX: 0,
            startY: 0,
            endX: 0,
            endY: 0,
            allPoints: [],
            currentPoints: [],
            isdraw: false,
            isBegin: false,
            selectArea: false,
            currentArea: null,
          };
        },
        mounted() {
          // new MyCanvas(this.$refs.canvas)
          this.canvas = this.$refs.canvas;
          this.$refs.canvas.width = 1014;
          this.$refs.canvas.height = 609;
          this.ctx = this.canvas.getContext("2d");

          this.canvas.addEventListener("mousedown", this.mousedown);
          this.canvas.addEventListener("mousemove", this.mousemove);
          this.canvas.addEventListener("mouseleave", this.mouseleave);
          this.canvas.addEventListener("dblclick", this.stopDraw);
          this.allPoints =
            JSON.parse(window.localStorage.getItem("allPoints")) || [];
          this.drawAllPoints(this.setDrawColor);
        },

        methods: {
          saveArea() {},
          closeDialog() {
            this.dialog = false;
            this.currentPoints = [];
            this.clearCanvas();
            this.drawAllPoints(this.setDrawColor);
          },
          clearCanvas() {
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
          },
          makeArea() {
            this.isdraw = true;
            this.isBegin = false;
            this.selectArea = false;
            this.$refs.canvas.style.cursor = "crosshair";
          },
          cancelMakeArea() {
            this.isdraw = false;
            this.isBegin = false;
            this.selectArea = false;
            this.$refs.canvas.style.cursor = "default";
          },
          selectAreaHandler() {
            this.isdraw = false;
            this.isBegin = false;
            this.selectArea = true;
            this.$refs.canvas.style.cursor = "default";
          },
          openBounding() {
            this.allPoints.forEach((areas) => {
              this.setBoundingStroke(areas.list);
            });
          },
          closeBounding() {
            this.clearCanvas();
            this.drawAllPoints(this.setDrawColor);
          },
          clearAll() {
            this.allPoints = [];
            window.localStorage.setItem(
              "allPoints",
              JSON.stringify(this.allPoints)
            );
            this.clearCanvas();
          },
          deleteArea() {
            this.allPoints = this.allPoints.filter(
              (item) => item.name !== this.currentArea.name
            );
            this.currentArea = null;
            window.localStorage.setItem(
              "allPoints",
              JSON.stringify(this.allPoints)
            );
            this.clearCanvas();
            this.drawAllPoints(this.setDrawColor);
          },
          setDrawColor(areas) {
            if (areas.id == this.currentArea?.id) {
              this.ctx.strokeStyle = "rgba(0,0,255,1)";
              this.ctx.fillStyle = "rgba(0,0,255,0.5)";
            } else {
              this.ctx.strokeStyle = "rgba(15,101,101,1)";
              this.ctx.fillStyle = "rgba(15,101,101,0.40)";
            }
          },
          drawAllPoints(setColorCalBack) {
            this.allPoints.forEach((areas) => {
              this.ctx.moveTo(areas.list[0].x, areas.list[0].y);
              this.ctx.beginPath();
              if (typeof setColorCalBack == "function") {
                setColorCalBack(areas);
              } else {
                this.ctx.strokeStyle = "rgba(255,0,0,1)";
                this.ctx.fillStyle = "rgba(255,0,0,0.5)";
              }

              areas.list.forEach((point) => {
                this.ctx.lineTo(point.x, point.y);
              });
              this.ctx.lineTo(areas.list[0].x, areas.list[0].y);
              this.ctx.fill();
              this.ctx.stroke();
              this.ctx.closePath();
              this.drawAreaName(areas);
            });
          },
          drawAreaName(areas) {
            const center = this.getPolygonAreaCenter(areas.list, areas.name);
            const name = areas.name.split(" ");

            this.ctx.fillStyle = "#fff"; // 文本颜色
            this.ctx.fontWeight = "bold";
            this.ctx.font = "12px sans-serif";
            this.ctx.textAlign = "left";
            this.ctx.textBaseline = "middle";
            let maxWidth = 0;
            name.forEach((item) => {
              const textMetrics = this.ctx.measureText(item);
              const textWidth = textMetrics.width;
              if (maxWidth < textWidth) {
                maxWidth = textWidth;
              }
            });

            const textHeight = parseInt(this.ctx.font);
            // 向上取整
            const nameLength = name.length;
            console.log(nameLength);
            center.y =
              nameLength >= 2
                ? center.y - (nameLength * textHeight) / 4
                : center.y;
            // console.log(center.y)
            // console.log(textHeight)
            // console.log(maxWidth)
            name.forEach((item) => {
              const textwidth = this.ctx.measureText(item).width;
              if (textwidth < maxWidth) {
                this.ctx.fillText(
                  item,
                  center.x + (maxWidth - textwidth) / 2,
                  center.y
                );
              } else {
                this.ctx.fillText(item, center.x, center.y);
              }
              center.y += textHeight + 3;
            });
          },
          drawCurrentLine() {
            if (!this.currentPoints[0]) return;
            this.ctx.moveTo(this.currentPoints[0].x, this.currentPoints[0].y);
            this.ctx.beginPath();
            this.currentPoints.forEach((point) => {
              this.ctx.lineTo(point.x, point.y);
            });
          },
          stopDraw() {
            this.isBegin = false;
            // this.isdraw = false
            const name = prompt("保存成功");
            const repeat = this.allPoints.some((item) => item.name === name);
            if (repeat) {
              this.$message.error("编号重复");
              return;
            }

            this.currentPoints.pop();
            this.allPoints.push({
              name: name,

              list: this.currentPoints,
            });
            window.localStorage.setItem(
              "allPoints",
              JSON.stringify(this.allPoints)
            );
            this.currentPoints = [];
            this.ctx.closePath();
            this.clearCanvas();
            this.drawAllPoints(this.setDrawColor);
            this.dialog = false;
          },

          mousedown(e) {
            if (this.isdraw) {
              this.isBegin = true;
              this.startX = e.offsetX;
              this.startY = e.offsetY;
              this.ctx.moveTo(this.startX, this.startY);
              this.ctx.beginPath();
              this.currentPoints.push({ x: this.startX, y: this.startY });
            }
            if (this.selectArea) {
              this.allPoints.forEach((areas) => {
                if (this.isPointInPolygon(e.offsetX, e.offsetY, areas.list)) {
                  this.currentArea = areas;
                  this.clearCanvas();
                  this.drawAllPoints(this.setDrawColor);
                }
              });
            }
          },
          mousemove(e) {
            if (this.isdraw && this.isBegin) {
              this.endX = e.offsetX;
              this.endY = e.offsetY;
              this.drawCurrentLine();
              this.clearCanvas();
              this.ctx.lineTo(this.endX, this.endY);
              this.ctx.lineTo(this.currentPoints[0].x, this.currentPoints[0].y);
              this.ctx.stroke();
              this.ctx.fillStyle = "rgba(255,255,255,0.5)";
              this.ctx.fill();
              this.drawAllPoints(this.setDrawColor);
            }
          },

          getPolygonAreaCenter(points, name) {
            let sum_x = 0;
            let sum_y = 0;
            let sum_area = 0;
            let p1 = points[1];
            for (var i = 2; i < points.length; i++) {
              let p2 = points[i];
              let area = this.Area(points[0], p1, p2);
              sum_area += area;
              sum_x += (points[0].x + p1.x + p2.x) * area;
              sum_y += (points[0].y + p1.y + p2.y) * area;
              p1 = p2;
            }
            name = name?.split(" ");
            let maxWidth = 0;
            name.forEach((item) => {
              const textMetrics = this.ctx.measureText(item);
              const textWidth = textMetrics.width;
              if (textWidth > maxWidth) {
                maxWidth = textWidth;
              }
            });
            // const textMetrics = this.ctx.measureText(name[0])
            // const textWidth = textMetrics.width
            const textHeight = parseInt(this.ctx.font);
            return {
              x: sum_x / sum_area / 3 - maxWidth / 2,
              y: sum_y / sum_area / 2.9 - textHeight / 2,
            };
          },
          Area(p0, p1, p2) {
            let area = 0.0;
            area =
              p0.x * p1.y +
              p1.x * p2.y +
              p2.x * p0.y -
              p1.x * p0.y -
              p2.x * p1.y -
              p0.x * p2.y;
            return area / 2;
          },
          getBoundingBox(vertices) {
            return {
              x: Math.min(...vertices.map((v) => v.x)),
              y: Math.min(...vertices.map((v) => v.y)),
              width:
                Math.max(...vertices.map((v) => v.x)) -
                Math.min(...vertices.map((v) => v.x)),
              height:
                Math.max(...vertices.map((v) => v.y)) -
                Math.min(...vertices.map((v) => v.y)),
            };
          },
          setBoundingStroke(list) {
            const bounding = this.getBoundingBox(list);
            this.ctx.beginPath();
            this.ctx.strokeStyle = "rgba(255,0,0,1)";
            this.ctx.strokeRect(
              bounding.x,
              bounding.y,
              bounding.width,
              bounding.height
            );
            this.ctx.closePath();
          },
          // 判断点击的哪个多边形内
          isPointInPolygon(x, y, points) {
            const n = points.length;
            let inside = false;
            const ray = { x: x + 1000, y }; // 射线长度为1000,向右发射

            for (let i = 0; i < n; i++) {
              const j = (i + 1) % n;
              const xi = points[i].x;
              const yi = points[i].y;
              const xj = points[j].x;
              const yj = points[j].y;

              // 检查射线与多边形边的交点
              if (
                yi > y !== yj > y &&
                x < ((xj - xi) * (y - yi)) / (yj - yi) + xi
              ) {
                inside = !inside;
              }
            }

            return inside;
          },
        },
      });
    </script>
  </body>
</html>

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值