canvas 系列学习笔记三实战例子《图片上画标注》

2022-09-08 16:17:47 浏览数 (1)

遇到一个新需求,在单据上标注有问题的地方,然后提交到后端。且旋转放大缩小标注点位置不变。

需求分析


imgae 是一个底图,上面是canvans 操作画图,底部层级可以是标签或者canvans 加载都可以。因为练习,所以选用canvans。

  1. 底部canvas drawimage
  2. 上面默认根据坐标画上方框
  3. 加上鼠标事件,点击确定点,move 确定宽高,离开即结束
  4. 画图以及处理旋转等问题

效果展示


代码


代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>背景图上画矩形标注</title>
  </head>
  <body>
    <button onclick="rotate()">旋转90度</button>
    <div id="container">
      <canvas id="canvas2dBg" width="500" height="500"></canvas>
      <canvas id="canvas2d" width="500" height="500"></canvas>
    </div>
  </body>
  <style>
    #container{
      position: absolute;
      background: red;
      width: 500px;
      height: 500px;
      left: 200px;
      top: 100px;
    }

    #canvas2dBg,#canvas2d{
      border: 1px solid;
      position: absolute;
    }

  </style>

  <script>
    let canvas2dBg = document.getElementById("canvas2dBg");
    let canvas2d = document.getElementById("canvas2d");
    if (canvas2d.getContext) {
      var ctxBg = canvas2dBg.getContext("2d");

      var ctx = canvas2d.getContext("2d");
      var img = new Image();

      img.onload = function () {
        ctxBg.drawImage(img, 0, 0);

        ctx.beginPath();
        ctx.strokeStyle = "red";
        ctx.strokeRect(0, 0, 100, 100);


      };
      img.src =
        "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png";

        var beginx, beginy, flag;

      canvas2d.onmousedown = (e) => {
        console.log(e);
        beginx = e.offsetX;
        beginy = e.offsetY;
        ctx.moveTo(beginx, beginy);
        flag = true;
      };

      canvas2d.onmousemove = (e) => {
        if (flag) {
          ctx.clearRect(0, 0, canvas2d.width, canvas2d.height);
          drawRect(beginx, beginy, e, ctx);
        }
      };

      canvas2d.onmouseup = (e) => {
        flag = false;
        ctx.clearRect(0, 0, canvas2d.width, canvas2d.height);
        drawRect(beginx, beginy, e, ctx);
      };
    }

    // 矩形
    function drawRect(beginx, beginy, e, canvas) {
      canvas.beginPath();
      var tx = e.offsetX - beginx;
      var ty = e.offsetY - beginy;
      canvas.rect(beginx, beginy, tx, ty);
      canvas.strokeStyle = "red";
      canvas.stroke();
    }


    function rotate() {
      let container = document.getElementById("container");
      container.style.transform = 'rotate(45deg)'
    }
  </script>
</html>

资源下载地址: https://download.csdn.net/download/ZY_FlyWay/86059815

0 人点赞