html5使用canvas实现小球碰撞反弹实例

使用 html5 中的 canvas, 实现小球相互碰撞并反弹,反弹算法比较简单.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bouncing balls</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Bouncing balls</h1>
    <canvas></canvas>

    <script src="main.js"></script>
</body>
</html>

style.css

html, body {
   
    margin: 0;
    padding: 0;
}

html {
   
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
    height: 100%;
}

body {
   
    overflow: hidden;
    height: inherit;
}

h1 {
   
    font-size: 2rem;
    letter-spacing: -1px;
    position: absolute;
    margin: 0;
    top: -4px;
    right: 5px;
    color: transparent;
    text-shadow: 0 0 4px white;
}

main.js

var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");

var WIDTH = document.documentElement.clientWidth;
var HEIGHT = document.documentElement.clientHeight;

canvas.width = WIDTH;
canvas.height = HEIGHT;

var config = 
  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
可以使用HTML5Canvas和JavaScript实现小球与边框碰撞反弹的效果。以下是一个简单的实现: 首先,在HTML中创建一个Canvas元素和一个JavaScript脚本: ```html <!DOCTYPE html> <html> <head> <title>Bouncing Ball</title> </head> <body> <canvas id="canvas" width="500" height="500"></canvas> <script src="script.js"></script> </body> </html> ``` 然后,在JavaScript中编写代码,实现小球的绘制、移动和碰撞反弹: ```javascript var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); // 小球的初始位置和速度 var x = canvas.width / 2; var y = canvas.height / 2; var dx = 2; var dy = -2; var ballRadius = 10; function drawBall() { ctx.beginPath(); ctx.arc(x, y, ballRadius, 0, Math.PI*2); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); } function draw() { // 每次移动前清除画布 ctx.clearRect(0, 0, canvas.width, canvas.height); // 绘制小球 drawBall(); // 如果小球碰到边缘,反弹 if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) { dx = -dx; } if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) { dy = -dy; } // 更新小球的位置 x += dx; y += dy; } setInterval(draw, 10); ``` 这段代码中,首先获取Canvas元素和绘图上下文对象。然后定义小球的初始位置和速度,并编写绘制小球和移动小球的函数。在draw函数中,每次先清除画布,然后绘制小球并判断是否碰到边缘,如果碰到边缘则反弹并更新小球的位置。最后使用setInterval函数让draw函数每隔一段时间执行一次,从而实现小球的动画效果。 这样,就可以实现小球与边框的碰撞反弹效果了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值