Vue实例——使用canvas封装polyline组件绘制一个五角星

本文介绍了如何在Vue组件中利用高德Polyline组件结合HTML5 canvas API,接收父组件传递的点坐标数组,实现折线绘制。详细步骤包括创建子组件、设置canvas大小、调用API绘制路径和填充。适合前端开发者学习canvas基础应用。
摘要由CSDN通过智能技术生成

1. 需求及效果

在看高德API时,发现有一个polyline组件,通过接收点的坐标数组,来绘制折线,正在看canvas API,就让我们一起试试吧。
在这里插入图片描述

2. 实施

思路:首先子组件需要接收父组件传递进来的点的数组,根据canvas API中的moveTo/lineTo/stroke来进行绘制

2.1 封装子组件

<template>
  <div class="polylinecanvas">
    <canvas id="polyline" :width="ctxWidth" :height="ctxHeight"></canvas>
  </div>
</template>
<script>
export default {
  props: {
    points: Array,
  },
  data() {
    return {
      receiveProps: [],
      // 设置幕布的宽高,避免出现因canvas画布分布太远超出范围而隐藏
      ctxHeight: 0,
      ctxWidth: 0,
    };
  },
  methods: {
    findMaxPoint() {
      this.points.forEach((v) => {
        if (v[0] > this.ctxWidth) {
          this.ctxWidth = v[0];
        }
        if (v[1] > this.ctxHeight) {
          this.ctxHeight = v[1];
        }
      });
    },
    drawPolyLine() {
      // 根据横竖坐标的最大值,设立canvas宽高,避免内容无法显示的问题
      this.receiveProps = this.points;
      let canvas = document.getElementById("polyline");
      if (canvas.getContext) {
        let ctx = canvas.getContext("2d");
        // 开始画图
        ctx.beginPath();
        // 画折线第一笔 moveTo 将画笔移动至首发点位置
        let firstPoint = this.points[0].flat();
        ctx.moveTo(firstPoint[0], firstPoint[1]);
        // 画折线剩余步骤,lineTo移动折线到指定位置
        // 剩余数组,用于化lineTo到不同的点
        let resArr = this.receiveProps.slice(1, this.points.length);
        resArr.forEach((v) => {
          let curPoint = v.flat();
          ctx.lineTo(curPoint[0], curPoint[1]);
        });
        // 设置折线颜色
        ctx.strokeStyle="red"
        // 设置填充颜色
        ctx.fillStyle="gold"
        // 填充线条
        ctx.stroke();
        // 绘制填充内容
        ctx.fill();
      }
    },
  },

  beforeDestroy() {
    // this.ctx = null;
  },
  async mounted() {
    if (this.points.length) {
      await this.findMaxPoint();
      await this.drawPolyLine();
    }
  },
};
</script>

2.2 在父组件中使用并传值

<template>
    <div class="polyinecanvas">
        <PolylineCanvas :points="pointsLine" />
    </div>
</template>
<script>
import PolylineCanvas from '../components/PolylineCanvas.vue';
export default {
    components:{
        PolylineCanvas,
    },
    data(){
        return {
            pointsLine:[
                [100,0],
                [159,181],
                [5,69],
                [195,69],
                [41,181],
                [100,0],
            ]
        }
    }
}
</script>

3. API阐述

  • beginPath() 新建一条路径
  • moveTo(x,y) 将画笔移动至起始点处
  • lineTo(x,y) 向下一个点开始画线
  • stroke() 线条形式
  • fill() 绘制实心
  • fillStyle=“red” 填充红色
  • strokeStyle=“gold” 折线金黄色

总结用法,希望可以帮助到你,
我是Ably,你无须超越谁,只要超越昨天的自己就好~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值