fabric.js 实现多个不规则图形

 效果图,是可拖拽,重新生成新的坐标

<canvas id="c" width="500" height="400" style="border:1px solid #ccc"></canvas>

<script src="https://unpkg.com/fabric@5.3.0/dist/fabric.min.js"></script>
<script>

  // 绑定画布
  const canvas = new fabric.Canvas('c');

  // 多边形的顶点
  let points = [
	  [
		 {id:1,x: 80, y: 80},
		 {id:2,x: 150, y: 40},
		 {id:3,x: 220, y: 80},
		 {id:4,x: 200, y: 190},
		 {id:5,x: 100, y: 160} 
	  ],
	  [
		 {id:12,x: 130, y: 80},
		 {id:23,x: 190, y: 40},
		 {id:32,x: 280, y: 80},
		 {id:42,x: 290, y: 190},
		 {id:52,x: 190, y: 160} 
	  ]
    
  ];


 let kssf =   points.map(el=>{
	const polygon1 = new fabric.Polygon(
	  el, // 顶点坐标集
	  {
	    fill: 'white', // 填充红色
	    stroke: 'red', // 边框黑色
	    strokeWidth: 2, // 边框粗细
	    objectCaching: false, // 当“true”时,对象缓存在另一个画布上。当“false”时,除非必要(clipPath)默认为 true,否则不缓存对象。默认是true
	    selectable: false, // 禁止选中
	    evented: false, // 当设置为“false”时,对象不能成为事件的目标。所有事件都会通过它传播。
		  opacity:0.5,
	  }
	);
	 
	 return polygon1;
 })

  // 圆形列表
  let circleList = [];

  // 循环所有定点并创建圆形
  points.forEach((el, index) => {
	  el.forEach((item,itemIdx)=>{
		  circleList.push(
		    new fabric.Circle({
		      left: item.x,
		      top: item.y,
			  parentIndex:index,
			  childrenIndex:itemIdx,
		      strokeWidth: 1,
		      radius: 4,
		      fill: '#fff',
		      stroke: 'red',
		      originX: 'center', // x轴方向以中心点为原点
		      originY: 'center', // y轴方向以中心点为原点
		      hasControls: false, // 不显示控制器
		      hasBorders: false, // 不显示控制器的边
		      cid: `circle-${index}` // 自定义属性
		    })
		  )
	  })
    
  });

  // 将多边形和圆形对象添加到画布中
  canvas.add(...kssf, ...circleList);

  // 监听画布上的元素移动事件
  canvas.on('object:moving', function(e) {
	  console.log("移动数据",e)
    // 当前移动的元素
    let target = e.target
    // 如果存在自定义属性和指定值就执行以下代码(本例主要筛选出刚刚创建的几个圆形)
    if ('cid' in target && target.cid.match(RegExp(/circle-/))) {
		let index1 = target.parentIndex;
		let index2 = target.childrenIndex;
		console.log(index1,index2)

        // 修改指定点顶点的x坐标
        points[index1][index2].x = target.left
        // 修改指定定点的y坐标
        points[index1][index2].y = target.top
        // 刷新画布
        canvas.renderAll()
    }
  });
</script>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值