uniapp开发微信小程序实现canvas带箭头直线

直接上代码(有兴趣可以扫码体验一下)
在这里插入图片描述

<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>
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值