约 3664 字
约 18 分钟
<canvas>
标签<canvas> 元素可被用来通过 JavaScript(Canvas API 或 WebGL API)绘制图形及图形动画。
height
: 该元素占用空间的高度,以 CSS 像素(px)表示,默认为 150。 moz-opaque
(废弃): 通过设置这个属性,来控制 canvas 元素是否半透明。如果你不想 canvas 元素被设置为半透明,使用这个元素将可以优化浏览器绘图性能。 width
: 该元素占用空间的宽度,以 CSS 像素(px)表示,默认为 300。 <canvas id="myCanvas">
</canvas>
<script>
// 2. 获取 Canvas 上下文
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 3. 设置画布尺寸为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 4. 定义小球对象
const ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 20,
dx: 4, // x轴速度
dy: 4, // y轴速度
color: `hsl(${Math.random() * 360}, 70%, 50%)`
};
// 5. 绘制小球的函数
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = ball.color;
ctx.fill();
ctx.closePath();
}
// 6. 动画循环
function animate() {
// 清空画布(半透明效果会产生拖尾)
ctx.fillStyle = "rgba(255, 255, 255, 0.1)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawBall();
// 碰撞检测(碰到边缘反弹)
if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0) {
ball.dx = -ball.dx;
ball.color = `hsl(${Math.random() * 360}, 70%, 50%)`; // 随机变色
}
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
ball.dy = -ball.dy;
ball.color = `hsl(${Math.random() * 360}, 70%, 50%)`;
}
// 更新位置
ball.x += ball.dx;
ball.y += ball.dy;
requestAnimationFrame(animate);
}
// 7. 启动动画
animate();
</script>
<canvas>
创建于 2025/5/22
更新于 2025/6/4