The effect
code
<! DOCTYPE html> <html lang="zh_CN">
<head>
<meta charset="UTF-8"> <title> marbles </title> <script SRC ="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas> <script> // global canvaslet canvas = document.getElementById("canvas");
let context = canvas.getContext("2d"); Class Ball{x = 100; y = 40; xSpeed = -2; ySpeed = -2;constructor() {};getX() {return this.x;
}
getY() {return this.y;
}
setX(x){
this.x = x;
}
setY(y){
this.y = y;
}
getXSpeed() {return this.xSpeed;
}
setXSpeed(xSpeed){
this.xSpeed = xSpeed;
}
getYSpeed() {return this.ySpeed;
}
setYSpeed(ySpeed){ this.ySpeed = ySpeed; } // Draw = () => {context.beginPath(); context.arc(this.x, this.y, 10, 0, Math.PI * 2,false); context.strokeRect(0, 0, 400, 400); context.fill(); }; Move = () => {this.x = this.x + this.xspeed; this.y = this.y + this.ySpeed; }; CheckCanvas = (panel) => {// left and rightif(this.x < 5 || this.x > 400 - 5){ this.xSpeed = -this.xSpeed; } / / aboveif(this.y < 0){ this.ySpeed = -this.ySpeed; } // below // hit the baffleif(this.y > 390 - 10){
if(this.x > panel.x && this.x < panel.xSize + panel.x){
this.ySpeed = -this.ySpeed;
}else{
alert("Game over."); this.x = 100; this.y = 10; }}}} // Add a baffle object class Panel{constructor() {}; // left x x = 200; // left y = 390; // Length xSize = 50; // width = 5;draw(){ context.fillRect(this.x, this.y, this.xSize, this.ySize); }} // Create a small ball objectletball = new Ball(); // Create a baffle objectletpanel = new Panel(); SetInterval (() => {// Clear the canvas context.clearRect(0, 0, 400, 400); // Draw the ball ball.draw(); // Draw a panel. Draw (); / / move the ball. The move (); Ball. CheckCanvas (panel); }, 10); $();"body").keydown((event) => {
if(event.keyCode == 37){ panel.x = panel.x - 5; // Move out of boundary problem handlingif(panel.x < 0){ panel.x = 0; }}if(event.keyCode == 39){ panel.x = panel.x + 5; // Move out of boundsif(panel.x + panel.xSize > 400){
panel.x = 400 - panel.xSize;
}
}
})
</script>
</body>
</html>
Copy the code
Train of thought
These are two objects, one dependent on the other. In the real coordinate judgment of collision detection, the two velocity components can be inverse after the collision is completed. Events are left and right events. Move. Real refresh when needed, i.e. the concept of frames