小球上下运动 跟着它划线就好了https://codesandbox.io/s/smoo...代码不多解释了,一看就懂。const screenSize = [300, 300]; const canvas = document.createElement("canvas"); [canvas.width, canvas.height] = screenSize; canvas.style.border = "1px solid black"; document.body.appendChild(canvas); const ctx = canvas.getContext("2d"); class Vec2 { constructor(x = 0, y = 0) { this.x = x; this.y = y; } add(other) { this.x += other.x; this.y += other.y; } } const shape = { pos: new Vec2(screenSize[0] / 2, screenSize[1] / 2), velocity: new Vec2(1, 1), radius: 10 }; const lines = [new Vec2(shape.pos.x, shape.pos.y)]; function loop() { update(); render(); requestAnimationFrame(loop); } function update() { // apply velocity shape.pos.add(shape.velocity); // collide with top and bottom const halfDownSize = 30; if ( shape.pos.y >= screenSize[1] / 2 + halfDownSize || shape.pos.y <= screenSize[1] / 2 - halfDownSize ) { lines.push(new Vec2(shape.pos.x, shape.pos.y)); shape.velocity.y = -shape.velocity.y; } } function render() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.save(); //set camera follow the circle ctx.translate(screenSize[0] / 2 - shape.pos.x, 0); // draw circle ctx.beginPath(); ctx.arc(shape.pos.x, shape.pos.y, shape.radius, 0, Math.PI * 2); ctx.fill(); // draw lines const drawLine = (p0, p1) => { ctx.beginPath(); ctx.moveTo(p0.x, p0.y); ctx.lineTo(p1.x, p1.y); ctx.stroke(); }; drawLine(lines[lines.length - 1], shape.pos); for (let i = 0; i < lines.length - 1; i++) { drawLine(lines[i], lines[i + 1]); } ctx.restore(); } requestAnimationFrame(loop);
小球上下运动 跟着它划线就好了
https://codesandbox.io/s/smoo...
代码不多解释了,一看就懂。