fabric.js画图(canvas画图 2d画图)相关

本文介绍了如何利用fabric.js库在canvas元素上进行2D图形绘制,包括基本操作和与Vue.js框架的结合应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
  <div style="position: relative">
    <canvas id="canvas"></canvas>
    <img id="expImg" :src="imgUrl" style="display: none" />
    <span id="areaA">A</span>
    <span id="areaB">B</span>
    <!-- <el-button
                type="danger"
                size="small"
                @click="newPoint"
                >新增绊线</el-button
              > -->
    <!-- <div @click="loadExpImg">加载背景图</div> -->
    <!-- <div class="draw-btn-group">
      <div :class="{ active: drawType == 'polygon' }" @click="drawPolygon">
        画多边形
      </div>
    </div> -->
  </div>
  <!-- <div class="maintenancePlanAdd">
    <div class="child-panel-title">
      <h2>图形标注</h2>
    </div>
    <div class="panel-body">
      <div class="demo">
        <canvas id="canvas" :width="width" :height="height"></canvas>
        <div class="draw-btn-group">
          <div :class="{active:drawType==''}" title="自由选择" @click="drawTypeChange('')">
           自由选择
          </div>
          <div :class="{active:drawType=='arrow'}" title="画箭头" @click="drawTypeChange('arrow')">
           画箭头
          </div>
          <div :class="{active:drawType=='text'}" title="文本输入框" @click="drawTypeChange('text')">
              文本输入框
          </div>
          <div :class="{active:drawType=='ellipse'}" title="画圆" @click="drawTypeChange('ellipse')">
            画圆
          </div>
          <div :class="{active:drawType=='rectangle'}" title="画矩形" @click="drawTypeChange('rectangle')">
           画矩形
          </div>
          <div :class="{active:drawType=='polygon'}" title="画多边形" @click="drawPolygon">
           画多边形
          </div>
          <div :class="{active:drawType=='pen'}" title="笔画" @click="drawTypeChange('pen')">
           笔画
          </div>
          <div :class="{active:drawType=='pentagram'}" title="五角星" @click="drawTypeChange('pentagram')">
           五角星
          </div>
          <div @click="uploadImg" title="从文件选择图片上传">
          从文件选择图片上传
          </div>
          <div @click="loadExpImg" title="加载背景图">
           加载背景图
          </div>
          <div @click="save" title="保存">
         保存
          </div>
        </div>
      </div>
    </div>
    <input type="file" @change="uploadImgChange" id="imgInput" accept="image/*" />
    <img id="img" :src="imgSrc" />
    <img id="expImg" src="../../assets/images/bg.png" />
  </div> -->
</template>
<script>
export default {
  name: "App",
  props: {
    type: [String],
    LinePointArray: [Array, Object, String],
    imgUrl: [String],
    algorithmType: [String],
    modeType: [String, Number, Object],
  },
  data() {
    return {
      width: 0,
      height: 0,
      rect: [],
      canvas: {},
      showMenu: false,
      x: "",
      y: "",

      mouseFrom: {},
      mouseTo: {},
      drawType: null, //当前绘制图像的种类
      canvasObjectIndex: 0,
      textbox: null,
      rectangleLabel: "warning",
      drawWidth: 2, //笔触宽度
      color: "#E34F51", //画笔颜色
      drawingObject: null, //当前绘制对象
      moveCount: 1, //绘制移动计数器
      doDrawing: false, // 绘制状态

      //polygon 相关参数
      polygonMode: false,
      pointArray: [],
      lineArray: [],
      activeShape: false,
      activeLine: "",
      line: {},

      delectKlass: {},
      imgFile: {},
      imgSrc: "",
      gh_position: {},
      lastPointArray: [], //传给后台的多边形坐标点
      lastPolygonPointArray: [],
      rectanglePointArr: [], //传给后台的矩形、直线坐标点
      /**
       * 记录每一次滑动生成线的坐标(格式为[x,y,x1,y1])
       */
      recordLinePointArray: [],
      /**
       * 最终生成需要上传给服务端的数组(格式为[[x,y,x1,y1],[x,y,x1,y1]])
       */
      // uploadLinePointArray:[],
      lineClassArray: [],
      selectIndex: -1,
      isCanvasSelect: false,
      selectLinePosition: {},
      isSelectPolygon: false,
      selectPolygonIndex: -1,
      polygonArray: [],
      currentTargetE: {},
    };
  },
  watch: {
    drawType() {
      this.canvas.selection = !this.drawType;
    },
    width() {
      this.canvas.setWidth(this.width);
    },
    height() {
      this.canvas.setHeight(this.height);
    },
    // modeType(){
    //   this.isAddBound();
    // }
  },
  mounted() {
      let _this = this
      console.log(_this.mousedown,'_this.mousedown')
    //   let mousedown = _this.mousedown
    this.canvas = new fabric.Canvas("canvas", {
      // skipTargetFind: false, //当为真时,跳过目标检测。目标检测将返回始终未定义。点击选择将无效
      selectable: false, //为false时,不能选择对象进行修改
      // selection: false   // 是否可以多个对象为一组
    });

    console.log(this.canvas,'this.canvas')
    this.loadExpImg();
    console.log(this.canvas.on,'this.canvas.on')
    this.canvas.selectionColor = "rgba(0,0,0,0.05)";
    this.canvas.on("mouse:down", e =>{
        _this.mousedown(e)
    });
    this.canvas.on("mouse:move", this.mousemove);
    this.canvas.on("mouse:up", this.mouseup);
    this.canvas.on("selection:created", this.canvasSelect);
    this.canvas.on("selection:cleared", this.canvasSelectCancel);
    this.canvas.on("object:moving", this.canvasMove);
    // this.canvas.on("object:scaling", this.canvasScale);
    this.canvas.on("object:rotating", this.canvasRotate);
    this.canvas.on("mouse:over", this.mouseOver);
    this.canvas.on("object");
    this.canvas.on("mouse:dblclick", this.dblclick);
    
    document.onkeydown = (e) => {
      // 键盘 delect删除所选元素
      if (e.keyCode == 46 || e.keyCode == 8) {
        this.deleteObj();
      }
      // ctrl+z 删除最近添加的元素
      if (e.keyCode == 90 && e.ctrlKey) {
        this.canvas.remove(
          this.canvas.getObjects()[this.canvas.getObjects().length - 1]
        );
        // 删除完成之后需要重新渲染
        this.canvas.renderAll()
      }
    };
  },
  methods: {
    showCanvas() {},
    canvasSelect(e) {
      if (this.drawType == "rectangle") {
        this.isCanvasSelect = true;
        console.log(e);
        return;
      }
      if (this.drawType == "Polygons") {
        this.isSelectPolygon = true;
        console.log("已经存在的多边形的数组", this.polygonArray);
        console.log(
          "输出已经选中多边形的坐标",
          this.canvas._activeObject.points
        );
        this.polygonArray.forEach((obj, index) => {
          obj.forEach((selectObj, selectIndex) => {
            if (
              selectObj.x == this.canvas._activeObject.points[0].x &&
              selectObj.y == this.canvas._activeObject.points[0].y
            ) {
              this.selectPolygonIndex = index;
              console.log("找到对应关系", this.selectPolygonIndex);
              return;
            }
          });
        });
      }
      this.isCanvasSelect = true;
      console.log("his.lineClassArray", this.lineClassArray);
      this.lineClassArray.forEach((item, index) => {
        if (item == e.target) {
          console.log("item", item);
          console.log("e.target", e.target);
          console.log("找到目标", index);
          this.selectIndex = index;
        }
      });
      this.gh_position = e.target.aCoords;
      this.stopDraw();
      console.log(this.canvas.item(0));
    },

    canvasSelectCancel(e) {
      this.isCanvasSelect = false;
      this.isSelectPolygon = false;
      this.selectPolygonIndex = -1;
      console.log("取消选中", this.uploadLinePointArray);
      document.getElementById("areaA").style.display = "none";
      document.getElementById("areaB").style.display = "none";
    },

    stopDraw() {
      if (this.drawType === "rectangle" || this.drawType === "line") {
        this.doDrawing = false;
      }
    },

    canvasMove(e) {
      if (this.type == "rectangle") {
        return;
      }
      if (this.type == "Polygons") {
        this.doDrawing = false;
        var lastArray = [];
        var changeX =
          this.canvas._activeObject.aCoords.br.x - this.gh_position.br.x;
        var changeY =
          this.canvas._activeObject.aCoords.br.y - this.gh_position.br.y;
        console.log("this.selectPolygonIndex]", this.selectPolygonIndex);
        console.log("this.polygonArray", this.polygonArray);
        console.log(
          "this.polygonArray[this.selectPolygonIndex]",
          this.polygonArray[this.selectPolygonIndex]
        );
        var selectTempArr = this.polygonArray[this.selectPolygonIndex];
        var finnalArr = [];
        selectTempArr.forEach((item, index) => {
          console.log(item);
          finnalArr.push({ x: item.x + changeX, y: item.y + changeY });
        });
        this.polygonArray.splice(this.selectPolygonIndex, 1, finnalArr);
        console.log("平移后的数组为", this.polygonArray);
        this.lastPolygonPointArray = this.polygonArray;
        this.$emit("imgLastPoint", this.lastPolygonPointArray);
      }
      this.lastPointArray = lastArray;
      // console.log("平移最终坐标为", this.lastPointArray);
      console.log(e);
      this.stopDraw();
    },

    canvasRotate(e) {
      console.log("canvasRotate");
      this.stopDra
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值