Show results:
One: Analyzing the problem:
- First of all, the static structure is a box, and there is a circle inside the box.
- The circle is moving inside the box.
- The process of moving reflects randomness.
- There will be a bounce effect when the circle hits the border of the box.
Two: Problem-solving ideas:
- The api used explicitly is the canvas canvas. Dynamic effects use timers.
- First draw out the static structure.
- Calculate the coordinates of the center of the circle as it moves.
- Calculate the conditions for the circle to bounce when it hits the border of the box.
- Effects are implemented dynamically using timers.
Three: Code implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态</title>
</head>
<body>
<canvas id="myCanvas" width="500px" height="500px" style="border: 1px solid black;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
function rand(mun) {
return Math.floor(Math.random() * mun + 1)
}
var arcX = 40;
var arcY = 40;
var arcR = 40;
var radX = rand(10);
var radY = rand(10);
setInterval(function () {
ctx.clearRect(0, 0, 500, 500);
arcX += radX;
arcY += radY;
if (arcX > c.width - arcR) {
radX = -radX;
}
if (arcX < arcR) {
radX = Math.abs(radX);
}
if (arcY > c.width - arcR) {
radY = -radY;
}
if (arcY < arcR) {
radY = Math.abs(radY);
}
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.arc(arcX, arcY, 40, 0, 2 * Math.PI);
ctx.fill();
}, 20)
</script>
</body>
</html>
Four: Cool case sharing: