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>

显示效果:

相关推荐
碳基生物猛吃膳食纤维6 分钟前
结合DEEPSEEK和CHATGPT弄了个小脚本,批量检查商品主图
前端
绝世唐门三哥10 分钟前
CSS 换行三剑客:overflow-wrap、word-break 与 white-space 完全指南
前端·css
程序员初一15 分钟前
我把跑了两年 WordPress 的机器重装了一遍,顺便把面板卸了
javascript
@大迁世界23 分钟前
告别 Go,拥抱 Rust
开发语言·golang·rust
SEO_juper24 分钟前
Node.js 重定向链检测工具:301 跳了几跳、有没有成环,一次看清
xml·开发语言·python·node.js·json·bash
kyriewen26 分钟前
别再用防抖做懒加载了:120 张图只加载出 4 张
前端·javascript·程序员
学逆向的26 分钟前
C 指针常量与常量指针
c语言·开发语言·网络安全
计算机魔术师31 分钟前
Hugging Face CEO 转评前 DOGE 研究人员用 AI 智能体渗透 Anthropic 系统事件
前端
IT_陈寒39 分钟前
刚解决一个 Java 并发问题,这坑踩得我怀疑人生
前端·人工智能·后端
前端一课40 分钟前
一个晚上,四个“小问题”:我重写了 12 章 ArkUI 笔记
前端