Canvas学习之路(七)
小球的碰撞检测
1.定义小球
ball = { x: 100, y: 100, r: 5, speed: 3, direction: Math.PI * 2 * Math.random() };
2.绘制小球:
update函数是更新小球用的,ctx.fillStyle = 'rgba(255, 255, 255, .05)';
这一句是用来增添小球的运动轨迹的。
function drawBall(ctx) { update(); ctx.fillStyle = 'rgba(255, 255, 255, .05)'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = '#000000'; ctx.beginPath(); ctx.arc(ball.x,ball.y, ball.r, 0, Math.PI*2, true); ctx.closePath(); ctx.fill() }
3.update函数
function update() { var dx = ball.x + Math.cos(ball.direction)*ball.speed; var dy = ball.y + Math.sin(ball.direction)*ball.speed; if (dx < 0 || dx > canvas.width || dy < 0 || dy > canvas.height){ ball.direction = Math.PI * 2 * Math.random(); update(); }else{ ball.x = dx; ball.y = dy; } }
4.调用上面的函数
function canvasApp() { var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); setInterval(function () { drawBall(context); }, 20); }
最后的效果如下:
相关推荐
大地飞鸿 2020-11-12
星星有所不知 2020-10-12
jinxiutong 2020-07-26
MIKUScallion 2020-07-05
songfens 2020-07-05
songfens 2020-06-11
songfens 2020-06-08
northwindx 2020-05-31
northwindx 2020-05-31
northwindx 2020-05-27
northwindx 2020-05-25
MIKUScallion 2020-05-25
jinxiutong 2020-05-10
xdyangxiaoromg 2020-05-10
大地飞鸿 2020-05-06
northwindx 2020-04-25