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>

显示效果:

相关推荐
fruge1 小时前
2025前端工程化与性能优化实战指南:从构建到监控的全链路方案
前端·性能优化
朱嘉鼎1 小时前
C语言之可变参函数
c语言·开发语言
aesthetician2 小时前
Node.js v25 重磅发布!革新与飞跃:深入探索 JavaScript 运行时的未来
javascript·node.js·vim
北冥湖畔的燕雀4 小时前
C++泛型编程(函数模板以及类模板)
开发语言·c++
demi_meng5 小时前
reactNative 遇到的问题记录
javascript·react native·react.js
QX_hao5 小时前
【Go】--map和struct数据类型
开发语言·后端·golang
你好,我叫C小白5 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
千码君20166 小时前
React Native:从react的解构看编程众多语言中的解构
java·javascript·python·react native·react.js·解包·解构
Evand J7 小时前
【MATLAB例程】基于USBL和DVL的线性回归误差补偿,对USBL和DVL导航数据进行相互补偿,提高定位精度,附代码下载链接
开发语言·matlab·线性回归·水下定位·usbl·dvl
lijun_xiao20098 小时前
前端最新Vue2+Vue3基础入门到实战项目全套教程
前端