<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() 方法点就会沿着路径运动了