canvas元素运动碰撞的小方块
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>方块运动碰撞</title>
<style>
* {
padding: 0;
margin: 0;
}
#canvas {
border: 1px solid red;
}
</style>
</head>
<body>
<canvas id="canvas">您的浏览器不支持canvas,请升级</canvas>
<script>
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');//获取画笔对象
let width=500,height=400,w=50,h=50,fillStyle='red',xFlag=1,yFlag=1,step=2,x=0,y=0;
// xFlag 1 :正方向 往右走 否则为0
// yFlag 1 :正方向 往下走 否则为0
canvas.width=width;
canvas.height=height;
let maxX=width-w;//最大的x位置
let maxY=height-h;//最大的y位置
setInterval(()=>{
// 每一次执行前都清空画布
ctx.clearRect(0,0,width,height);
// 判断方向
if(xFlag == 1){
x+=step;
if(x>=maxX){
xFlag=0;
}
}else if(xFlag == 0){
x += -step;
if(x<=0){
xFlag=1;
}
}
// 判断方向
if(yFlag == 1){
y+=step;
if(y>=maxY){
yFlag=0;
}
}else if(yFlag == 0){
y += -step;
if(y<=0){
yFlag=1;
}
}
ctx.beginPath();
ctx.fillStyle=fillStyle;
ctx.fillRect(x,y,w,h);
},30)
</script>
</body>
</html>
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634578.html