fabricjs 添加直线宽度,实现类似道路效果

javascript 复制代码
<template>
  <canvas
    id="canvas"
    width="1200"
    height="800"
    style="border: 1px solid #ccc"
  />
</template>

<script>
import { fabric } from 'fabric'
export default {
  mounted() {
    this.init()
  },
  methods: {
      poitnl(x1, y1, x2, y2, leftwidth, rightWidth) {
        // (x1, y1) 和 (x2, y2) 分别为开始点和结束两点坐标 leftwidth 为点1→点2 左侧宽度,rightWidth 为点1→点2 右侧宽度,
      const angleRadians = Math.atan2(y2 - y1, x2 - x1)
      // 计算左侧和右侧宽度的偏移坐标
      const leftOffsetX = leftwidth * Math.cos(angleRadians + Math.PI / 2)
      const leftOffsetY = leftwidth * Math.sin(angleRadians + Math.PI / 2)
      const rightOffsetX = rightWidth * Math.cos(angleRadians - Math.PI / 2)
      const rightOffsetY = rightWidth * Math.sin(angleRadians - Math.PI / 2)
      // 构造新的多边形点
      const points = {
        leftp: [// 左侧绘制偏移点
          x1 + leftOffsetX,
          y1 + leftOffsetY,
          x2 + leftOffsetX,
          y2 + leftOffsetY
        ],
        rightp: [ // 右侧绘制偏移点
          x2 + rightOffsetX,
          y2 + rightOffsetY,
          x1 + rightOffsetX,
          y1 + rightOffsetY
        ]
      }
      return points
    },

    init() {
      const point = [0, 300, 600, 300]
      const canvas = new fabric.Canvas('canvas')
      const line = new fabric.Line(point, {
        stroke: 'green', // 笔触颜色
        strokeWidth: 10, // 笔触宽度
        hasRotatingPoint: false, // 选中时是否能够旋转
        originX: 'center',
        originY: 'center',
        opacity: 0.6
      })
      canvas.add(line)
      const linel = new fabric.Line(
        this.poitnl(point[0], point[1], point[2], point[3], 50, 50).rightp,
        {
          stroke: 'red', // 笔触颜色
          strokeWidth: 100, // 笔触宽度
          hasRotatingPoint: false, // 选中时是否能够旋转
          originX: 'center',
          originY: 'center',
          opacity: 0.3
        }
      )
      canvas.add(linel)
    }
  }
}
</script>

显示效果:

相关推荐
IT_陈寒37 分钟前
Redis那个过期删除策略,差点让我线上崩了
前端·人工智能·后端
jianqiang.xue40 分钟前
Espressif-IDE进入维护模式:乐鑫把ESP32开发的宝押给VS Code
前端·css·ide
特创数字科技1 小时前
纯本地离线运行的文档脱敏工具(技术分享)
前端·驱动开发·python
心之语歌1 小时前
uni-app uts原生插件开发:uts 与 Kotlin 交互踩坑实录(附解决方案)
前端·后端
再吃一根胡萝卜2 小时前
DSH 插件数据链路:Host 管数据,Client 只管画
前端
feixing_fx2 小时前
CSS 变量(Custom Properties):构建可扩展的主题切换系统
前端·css·前端框架·html·css3
布莱克6052 小时前
Swift 循环与控制转移详解:从 for-in 到标签跳转
开发语言·ssh·swift·循环
敲上瘾3 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
十有八七3 小时前
手搓 Agent(一):先有大脑——大模型只会做一件事
前端·人工智能·后端
锋行天下3 小时前
「踩坑实录」给 LangGraph Agent 接两个 FastMCP,我被 langchain 偷偷改了工具名
前端·人工智能·后端