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,你无须超越谁,只要超越昨天的自己就好~