# 如何获得带有声音的警报盒？

const ctx = document.getElementById("Canvas").getContext("2d");
const containerR = 150;
const size = containerR * 2
ctx.canvas.width = ctx.canvas.height = size;
ctx.globalAlpha = 0.8

const getBall = (x, y, dx, dy, r, color) => ({x, y, dx, dy, r, color});

const balls = [
getBall(size / 2, size - 30, 1, 1, 8, "Green"),
getBall(size / 3, size - 50, 1, 1, 8, "Green"),
getBall(size / 4, size - 60, 1, 1, 8, "Green"),
getBall(size / 2, size / 5,  1, 1, 8,  "Green"),
];

const drawBall = (ball) => {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
ctx.fillStyle = ball.collider ? "red" : ball.color;
ctx.fill();
ctx.closePath();
}

const updatePos = (ball) => {

ball.x += ball.dx;
ball.y += ball.dy;
const dx = ball.x - containerR;
const dy = ball.y - containerR;

if (Math.sqrt(dx * dx + dy * dy) >= containerR - ball.r) {
const v = Math.sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
const angleToCollisionPoint = Math.atan2(-dy, dx);
const oldAngle = Math.atan2(-ball.dy, ball.dx);
const newAngle = 2 * angleToCollisionPoint - oldAngle;
ball.dx = -v * Math.cos(newAngle);
ball.dy = v * Math.sin(newAngle);
}
}

const collides = (a, b) => (Math.hypot(Math.abs(a.x - b.x), Math.abs(a.y - b.y)) < (a.r + b.r));

function engine() {
//console.clear(); // Clear console test messages
mydiv.textContent =" ";
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

balls.forEach((a, ai) => {
a.collider = undefined;

balls.forEach((b, bi) => {
if (bi === ai) return; // Don't look at self
if (collides(a, b)) a.collider = b; // Store the colliding B ball
});

if (a.collider) { // If ball has a collider:
//console.log(`\${a.color[0]} → ← \${a.collider.color[0]}`);
}

updatePos(a);
drawBall(a);
});

requestAnimationFrame(engine);
}

engine();
<style>
canvas {
background: #eee;
margin: 0 auto;