canvas + svg 让点沿着路径运动

    <canvas id="canvas" width="1000" height="1000" style="width: 50vh;height: 50vh;"></canvas>
<svg t="1716468064482" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2958" width="200" height="200"><path d="M932.5056 955.5456a22.9376 22.9376 0 0 1-16.2816-6.7584l-154.9824-154.9312a414.72 414.72 0 1 1 111.4112-161.8944 23.04 23.04 0 0 1-43.1104-16.384 369.7664 369.7664 0 1 0-84.1216 129.8432 22.9888 22.9888 0 0 1 32.5632 0L948.7872 916.48a23.04 23.04 0 0 1-16.2816 39.3216z" fill="#4D4D4D" p-id="2959"></path></svg>

       
 const canvas = document.getElementById("canvas");
        const ctx = canvas.getContext("2d");

        const pathElement = document.querySelector('path');
        const path = pathElement.getAttribute('d');

        const strokePath = new Path2D(path);
        ctx.stroke(strokePath);



        // 1.获取路线总长度
        const pathLength = pathElement.getTotalLength();

        // 2. 获取路线起点的坐标
        const { x, y } = pathElement.getPointAtLength(0);

        let position = 0;
function move() {
  // 首先先要把画布擦干净
  ctx.clearRect(0, 0, 1000, 1000);
  // 获取xy坐标
	const {x, y} = pathElement.getPointAtLength(position);
    // 绘制小球
    ctx.fillStyle = 'red';//填充颜色-实心圆
    ctx.globalCompositeOperation = 'lighter'
    ctx.fill();//画实心圆
    ctx.beginPath();
    ctx.arc(x, y, 10, 0, Math.PI * 2)
	// 更新位移的长度
 
    if(position>pathLength){
        position = 0
    }
    position+=10;
  // 在这里调用requestAnimationFrame方法,将move函数传进去,就可以实现循环调用了。
  requestAnimationFrame(move);
}
move()

执行下面的代码可以用canvas 画出svg的图形

画出点沿着canvas画出的路径运动 只需要 执行  move() 方法点就会沿着路径运动了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值