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>

显示效果:

相关推荐
大阳1236 分钟前
线程(基本概念和相关命令)
开发语言·数据结构·经验分享·算法·线程·学习经验
YA33314 分钟前
java基础(九)sql基础及索引
java·开发语言·sql
开发者小天20 分钟前
为什么 /deep/ 现在不推荐使用?
前端·javascript·node.js
如白驹过隙1 小时前
cloudflare缓存配置
前端·缓存
excel1 小时前
JavaScript 异步编程全解析:Promise、Async/Await 与进阶技巧
前端
奇树谦1 小时前
QT|windwos桌面端应用程序开发,当连接多个显示器的时候,如何获取屏幕编号?
开发语言·qt
Jerry说前后端1 小时前
Android 组件封装实践:从解耦到架构演进
android·前端·架构
weixin_307779131 小时前
VS Code配置MinGW64编译GNU 科学库 (GSL)
开发语言·c++·vscode·算法
froginwe112 小时前
HTML 框架:构建网页布局的基石
开发语言
步行cgn2 小时前
在 HTML 表单中,name 和 value 属性在 GET 和 POST 请求中的对应关系如下:
前端·hive·html