1 Star 2 Fork 2

三碗不下桌 / canvas

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
矩形碰撞检测.html 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
三碗不下桌 提交于 2020-11-29 17:38 . canvas
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>矩形碰撞检测</title>
</head>
<body style="margin: 0;padding: 0;" onload="draw()">
<canvas id="canvas" width="800px" height="400px" style="border: solid 1px #000;"></canvas>
<script>
function draw(){
let canvas = document.querySelector("#canvas");
if(canvas.getContext){
//创建context对象
let cvsCtx = canvas.getContext("2d");
//1.绘制图像
//2.清除画布
//3.更新位置
//4.绘制图像 2. 3. 4.
//面向对象
function Rect(x,y,width,height,color,speedX){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
this.speedX = speedX;
}
Rect.prototype.draw = function(){
cvsCtx.beginPath();
cvsCtx.fillStyle = this.color;
cvsCtx.fillRect(this.x, this.y, this.width, this.height);
cvsCtx.closePath();
}
Rect.prototype.move = function(){
//更新位置
this.x += this.speedX;
if(this.x > canvas.width-this.width || this.x < 0){
this.speedX *= -1;
}
}
function init(){
//清除画布
cvsCtx.clearRect(0, 0, canvas.width, canvas.height);
rect1.draw();
rect1.move();
rect2.draw();
rect2.move();
//检测
if(isRectHit(rect1,rect2)){
rect1.speedX *= -1;
rect2.speedX *= -1;
}
//请求关键帧动画
window.requestAnimationFrame(init);
}
function isRectHit(rect1,rect2){
let min1 = rect1.x;
let min2 = rect2.x;
let max1 = rect1.x + rect1.width;
let max2 = rect2.x + rect2.width;
let min3 = Math.max(min1,min2);
let max3 = Math.min(max1,max2);
if(min3<=max3){
return true;
}
return false;
}
let rect1 = new Rect(0,200,150,150,'pink',4);
let rect2 = new Rect(640,200,150,150,'skyblue',4);
init();
isRectHit(rect1,rect2);
}
}
</script>
</body>
</html>
JavaScript
1
https://gitee.com/RichQin/canvas.git
git@gitee.com:RichQin/canvas.git
RichQin
canvas
canvas
master

搜索帮助