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>

显示效果:

相关推荐
杨哥带你写代码几秒前
探索Perl的自动清洁工:垃圾收集机制全解析
开发语言·perl
super_Dev_OP3 分钟前
Web3 社交领域的开发技术
大数据·前端·人工智能·前端框架
半夏知半秋8 分钟前
R语言学习笔记6-数据框
开发语言·笔记·学习·信息可视化·r语言
2401_8441375710 分钟前
PHP证件照制作微信小程序系统源码
大数据·开发语言·微信小程序·小程序·微信开放平台
**之火17 分钟前
ES6 Module 的语法(十二)
前端·ecmascript·es6
xiaogg367834 分钟前
Electron 跨平台桌面应用开发工具
前端·javascript·electron
踏过山河,踏过海38 分钟前
快速测试electron环境是否安装成功
前端·javascript·electron
开源博客41 分钟前
如何在 Vue 项目中优雅地使用图标
前端·ui·vue·icon·用户界面·图标
程序员二师兄1 小时前
高效实现React服务器端渲染:从renderToString到renderToPipeableStream
前端·javascript·react.js