代码拉取完成,页面将自动刷新
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<style>
canvas{
box-shadow: 0 0 10px #999;
}
</style>
<body onload="init()">
<canvas height="300" width="400" id="canvas">
浏览器不支持
</canvas>
</body>
</html>
<script>
function init(){
var canvas = document.getElementById("canvas");
if(!canvas.getContext){
return
}
var ctxt = canvas.getContext('2d')
function Ball(x,y,r,speedX,speedY,color) {//小球对象
this.x = x;
this.y = y;
this.r = r;
this.speedX = speedX;
this.speedY = speedY;
this.color = color;
}
Ball.prototype.circle = function(){//小球
ctxt.beginPath();
ctxt.fillStyle = this.color
ctxt.arc(this.x,this.y,this.r,0,Math.PI*2)
ctxt.stroke()
ctxt.fill()
}
Ball.prototype.move = function(){//小球运动
this.x += this.speedX;
if(this.x > canvas.width-this.r){//判断是否碰到边缘,如果碰到,往回弹
this.speedX *= -1
}else if(this.x < this.r){
this.speedX *= -1
}
this.y += this.speedY;
if(this.y>canvas.height-this.r){
this.speedY *= -1
}else if(this.y<this.r){
this.speedY *= -1
}
};
var ball = new Ball(20,30,10,10,5,'red');
var ball2 = new Ball(90,30,10,8,9,'green');
ball.circle();
ball.move();
ball2.circle();
ball2.move();
function animate(){
ctxt.clearRect(0,0,canvas.width,canvas.height);
ball.circle();
ball.move();
ball2.circle();
ball2.move();
if(ballIsHit(ball,ball2)){//判断两个小球之间是否碰撞
ball.speedY *= -1;
ball.speedX *= -1;
ball2.speedX *= -1;
ball2.speedY *= -1;
}
window.requestAnimationFrame(animate)
}
animate();
function ballIsHit(ball,ball2){//小球碰撞
var minX1 = ball.x-ball.r;
var minX2 = ball2.x-ball2.r;
var minY1 = ball.y-ball.r;
var minY2 = ball2.y-ball2.r;
var maxX1 = ball.x + ball.r;
var maxX2 = ball2.x + ball2.r;
var maxY1 = ball.y + ball.r;
var maxY2 = ball2.y + ball2.r;
var minX = Math.max(minX1,minX2);
var minY = Math.max(minY1,minY2);
var maxX = Math.min(maxX1,maxX2);
var maxY = Math.min(maxY1,maxY2);
if(minX<maxX && minY < maxY){//左边的小球的右侧小于右边小球的左侧 上侧小于下侧 就发生碰撞
console.log('000');
return true
}
}
}
</script>
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。