canvas-台球玩法
一、思路
- 绘制台球案板
- 画球方法
- 加上球移动的动作(控制透明度)
- 鼠标点击,球开始发射,匀速(实际有摩擦力,要速度减少),碰到案板要返回,速度或者说是每次位移的距离
- 鼠标移动,来放置球的位置
- 鼠标移出,停止动作
二、代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>controlBall</title> </head> <body> <canvas id="canvas" width="600" height="300"></canvas> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var raf; var running = false; // 绘制边框 function drawRect() { ctx.beginPath(); ctx.rect(0,0,canvas.width,canvas.height); ctx.strokeStyle = '#000'; ctx.stroke(); } var ball = { x: 100, y: 100, vx: 5, vy: 1, radius: 25, color: 'blue', draw: function() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); } }; function clear() { ctx.fillStyle = 'rgba(255,255,255,0.3)'; ctx.fillRect(0,0,canvas.width,canvas.height); } function draw() { clear(); drawRect(); ball.x += ball.vx; ball.y += ball.vy; if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } ball.draw(); raf = window.requestAnimationFrame(draw); } canvas.addEventListener('mousemove', function(e){ if (!running) { clear(); drawRect(); ball.x = e.clientX; ball.y = e.clientY; ball.draw(); } }); canvas.addEventListener('click',function(e){ if (!running) { raf = window.requestAnimationFrame(draw); running = true; } }); canvas.addEventListener('mouseout', function(e){ window.cancelAnimationFrame(raf); running = false; }); ball.draw(); drawRect(); </script> </body> </html>