直接上代码(有兴趣可以扫码体验一下)
<template>
<view class="canvas-content">
<!-- 画布 -->
<canvas
class="mycanvas"
disable-scroll="true"
canvas-id="Canvas"
id="Canvas"
>
</canvas>
</view>
</template>
<script>
export default {
data() {
return {
ctx: null
}
},
onLoad() {
this.ctx = uni.createCanvasContext("Canvas")
},
onShow () {
this.drawLineArrow(10, 10, 100, 10)
},
methods: {
drawLineArrow (fromX, fromY, toX, toY) {
var headlen = 10;//自定义箭头线的长度
var theta = 45;//自定义箭头线与直线的夹角,个人觉得45°刚刚好
var arrowX, arrowY;//箭头线终点坐标
// 计算各角度和对应的箭头终点坐标
var angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI;
var angle1 = (angle + theta) * Math.PI / 180;
var angle2 = (angle - theta) * Math.PI / 180;
var topX = headlen * Math.cos(angle1);
var topY = headlen * Math.sin(angle1);
var botX = headlen * Math.cos(angle2);
var botY = headlen * Math.sin(angle2);
this.ctx.beginPath();
arrowX = toX + topX;
arrowY = toY + topY;
//画上边箭头线
this.ctx.moveTo(arrowX, arrowY);
this.ctx.lineTo(toX, toY);
arrowX = toX + botX;
arrowY = toY + botY;
//画下边箭头线
this.ctx.lineTo(arrowX, arrowY);
this.ctx.stroke();
this.ctx.closePath();
//画直线
this.ctx.beginPath();
this.ctx.moveTo(fromX, fromY);
this.ctx.lineTo(toX, toY);
this.ctx.stroke();
this.ctx.draw(true);
}
}
}
</script>