vue版canvas选择区域

话不多说直接上代码
在这里插入图片描述
兼容触摸和pc
放组件中可以直接使用。这里注意外框要用百分比高度和宽度包裹上

<template>
  <div class="selectquyu">
    <canvas
      :id="canvasid"
      class="huabu"
      :width="width"
      :height="height"
    ></canvas>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      canvasid: "alldian",
      width: "",
      height: "",
      selectColor: "#fff",
      color: "#28B1D9",
      areaColor: "rgba(40, 177, 217, 0.2)",
      dianyi1: {
        x: 70,
        y: 100,
        selectColor: "",
      },
      dianyi2: {
        x: 140,
        y: 25,
        selectColor: "",
      },
      dianyi3: {
        x: 70,
        y: 150,
        selectColor: "",
      },
      dianyi4: {
        x: 140,
        y: 150,
        selectColor: "",
      },
    };
  },
  mounted() {
    this.dowa();
  },
  methods: {
    dowa() {
      this.width = document.querySelector(".selectquyu").offsetWidth;
      this.height = document.querySelector(".selectquyu").offsetHeight;
      setTimeout(() => {
        var canelem = document.getElementById(this.canvasid);
        var cxt = canelem.getContext("2d");
        this.initCanvas(cxt, this.width, this.height);
        let { dianyi1, dianyi2, dianyi3, dianyi4 } = this;
        this.isontouchend()?//判断是否支持触屏
        this.touchesEvent(cxt, canelem, [dianyi1,dianyi2,dianyi3,dianyi4]):
        this.mouseEvent(cxt, canelem, [dianyi1, dianyi2, dianyi3, dianyi4]);
      }, 0);
    },
    isontouchend() {//判断是否支持触屏
      return "ontouchend" in document ? true : false;
    },
    mouseEvent(cxt, element, dianyi) {
      let xuznzhong = "";
      element.onmousedown = (e) => {
        console.log("1111", e);
        var layerX = e.layerX; //计算出触摸距离当前画布的距离好进行移动
        var layerY = e.layerY;
        for (var i = 0; i < dianyi.length; i++) {
          //进行循环查看哪个点是当前点击的点
          xuznzhong = this.isBox(dianyi[i], layerX, layerY);
          if (xuznzhong) {
            xuznzhong.selectColor = this.selectColor;
            break;
          }
        }
        if (xuznzhong) {
          element.onmousemove = (e) => {
            xuznzhong.x = e.layerX;
            xuznzhong.y = e.layerY;
            this.initCanvas(cxt, this.width, this.height);
          };
        }
      };
      element.onmouseup = (e) => {
        if (xuznzhong) {
          xuznzhong.selectColor = "";
          xuznzhong = null;
        }
        element.onmousemove = null;
        this.initCanvas(cxt, this.width, this.height);
      };
    },
    touchesEvent(cxt, element, dianyi) {
      //触屏事件
      var pingmuTop = element.getBoundingClientRect().top; //画布距离屏幕上面的距离  这里要计算出触摸距离当前画布的距离好进行移动
      var pingmuLeft = element.getBoundingClientRect().left; //画布距离屏幕左面的距离
      let xuznzhong = "";
      element.ontouchstart = (e) => {
        var layerX = e.touches[0].pageX - pingmuLeft; //计算出触摸距离当前画布的距离好进行移动
        var layerY = e.touches[0].pageY - pingmuTop;
        for (var i = 0; i < dianyi.length; i++) {
          //进行循环查看哪个点是当前点击的点
          xuznzhong = this.isBox(dianyi[i], layerX, layerY);
          if (xuznzhong) {
            xuznzhong.selectColor = this.selectColor;
            break;
          }
        }
        if (xuznzhong) {
          element.ontouchmove = (e) => {
            xuznzhong.x = e.touches[0].pageX - pingmuLeft;
            xuznzhong.y = e.touches[0].pageY - pingmuTop;
            this.initCanvas(cxt, this.width, this.height);
          };
        }
      };
      element.ontouchend = (e) => {
        if (xuznzhong) {
          xuznzhong.selectColor = "";
          xuznzhong = null;
        }
        element.ontouchmove = null;
        this.initCanvas(cxt, this.width, this.height);
      };
    },
    initCanvas(cxt, width, height) {
      //初始化画布
      let { dianyi1, dianyi2, dianyi3, dianyi4 } = this;
      cxt.clearRect(0, 0, width, height);
      this.linedow(dianyi1, dianyi2, dianyi3, dianyi4, cxt);
      this.dianyidow(dianyi1.x, dianyi1.y, cxt, dianyi1.selectColor);
      this.dianyidow(dianyi2.x, dianyi2.y, cxt, dianyi2.selectColor);
      this.dianyidow(dianyi3.x, dianyi3.y, cxt, dianyi3.selectColor);
      this.dianyidow(dianyi4.x, dianyi4.y, cxt, dianyi4.selectColor);
    },
    dianyidow(x, y, cxt, selectColor) {
      //画实心圆
      cxt.fillStyle = selectColor || this.color;
      cxt.beginPath();
      cxt.arc(x, y, 18, 0, Math.PI * 2, true);
      cxt.closePath();
      cxt.fill();
      cxt.beginPath();
      cxt.arc(x, y, 18, 0, Math.PI * 2, true);
      cxt.lineWidth = 4;
      cxt.strokeStyle = this.color;
      cxt.stroke(); //画空心圆
      cxt.closePath();
    },
    linedow(dianyi1, dianyi2, dianyi3, dianyi4, cxt) {
      let { color, areaColor } = this;
      //画线
      cxt.beginPath();
      cxt.moveTo(dianyi1.x, dianyi1.y);
      cxt.lineTo(dianyi2.x, dianyi2.y);
      cxt.lineTo(dianyi4.x, dianyi4.y);
      cxt.lineTo(dianyi3.x, dianyi3.y);
      cxt.lineWidth = 2;
      cxt.strokeStyle = color;
      cxt.closePath();
      cxt.fillStyle = areaColor;
      cxt.fill();
      cxt.stroke();
    },
    isBox(data, x, y, range = 22) {
      //判断是否选中 选中返回当前点的坐标
      if (
        data.x - range < x &&
        data.x + range > x &&
        data.y - range < y &&
        data.y + range > y
      ) {
        return data;
      } else {
        return null;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.selectquyu {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 100;
  .kuang {
    position: relative;
    width: 100px;
    height: 100px;
    border: 1px solid #27b2d9;
    background-color: rgba($color: #28b1d9, $alpha: 0.2);
    .dian {
      position: absolute;
      width: 18px;
      height: 18px;
      border: 4px solid #01deff;
      // background-color: #28B1D9;
      background-color: #fff;
      border-radius: 50%;
    }
    .dian:nth-child(1) {
      left: -10px;
      top: -10px;
    }
    .dian:nth-child(2) {
      left: -10px;
      bottom: -10px;
    }
    .dian:nth-child(3) {
      right: -10px;
      top: -10px;
    }
    .dian:nth-child(4) {
      right: -10px;
      bottom: -10px;
    }
  }
}
</style>
### Vue.js 中 Canvas 插入文字的实现方法 在 Vue.js 项目中,可以通过 HTML 的 `<canvas>` 元素结合 JavaScript 来实现在画布上插入文字的功能。以下是具体的实现方式: #### 实现步骤说明 1. **引入 Canvas 元素** 首先,在模板部分定义一个 `<canvas>` 元素,并为其绑定宽高属性。 2. **操作 Canvas 上下文** 使用 `getContext('2d')` 方法获取 Canvas 的绘图上下文对象,然后调用其提供的 API 绘制文字。 3. **动态更新文字内容** 利用 Vue 数据响应特性,当数据发生变化时重新渲染 Canvas 图形。 --- #### 示例代码 以下是一个完整的 Vue.js 示例,展示如何在 Canvas 区域插入并动态更新文字[^1]。 ```vue <template> <div id="app"> <!-- 输入框用于修改文字 --> <input type="text" v-model="textToDraw" placeholder="输入要绘制的文字" /> <!-- Canvas 元素 --> <canvas ref="myCanvas" width="400" height="200"></canvas> </div> </template> <script> export default { data() { return { textToDraw: "默认文字", // 要绘制的文字,默认值 }; }, watch: { // 当文本变化时重绘 Canvas textToDraw(newText) { this.drawTextOnCanvas(); }, }, mounted() { // 初始化时绘制一次 this.drawTextOnCanvas(); }, methods: { drawTextOnCanvas() { const canvas = this.$refs.myCanvas; const ctx = canvas.getContext("2d"); // 清除之前的绘制内容 ctx.clearRect(0, 0, canvas.width, canvas.height); // 设置字体样式 ctx.font = "30px Arial"; ctx.fillStyle = "#333"; // 计算文字居中的位置 const x = canvas.width / 2; const y = canvas.height / 2; // 文字水平垂直居中 ctx.textAlign = "center"; ctx.textBaseline = "middle"; // 绘制文字到 Canvas ctx.fillText(this.textToDraw, x, y); }, }, }; </script> <style scoped> #app { display: flex; flex-direction: column; align-items: center; } canvas { border: 1px solid #ccc; } </style> ``` --- #### 关键点解析 1. **动态绑定文字** 使用 Vue 的双向绑定功能 (`v-model`) 将用户输入与内部状态关联起来,从而实现动态更新效果。 2. **Canvas 基本操作** - `ctx.font`: 定义字体大小和样式。 - `ctx.fillStyle`: 设定文字颜色。 - `ctx.fillText(text, x, y)`: 在指定坐标 `(x, y)` 处绘制文字。 3. **清除旧内容** 每次重新绘制前需调用 `clearRect()` 方法清空 Canvas,防止新内容叠加在旧内容之上。 4. **文字对齐设置** 使用 `textAlign` 和 `textBaseline` 属性可以方便地控制文字的位置和对齐方式。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值