Canvas教学:一个彩色圆环在画布上旋转,并且颜色不断渐变-由Deepseek产生
·
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>极简趣味Canvas | 旋转彩虹环</title>
<style>
body {
background: #0a0f1e;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
padding: 20px;
}
canvas {
border-radius: 24px;
box-shadow: 0 10px 25px rgba(0,0,0,0.3);
background: #000;
}
</style>
</head>
<body>
<canvas id="funCanvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('funCanvas');
const ctx = canvas.getContext('2d');
let angle = 0; // 旋转角度
function draw() {
// 清屏
ctx.fillStyle = '#0a0f1e';
ctx.fillRect(0, 0, 500, 500);
// 移动坐标系到画布中心
ctx.save();
ctx.translate(250, 250);
ctx.rotate(angle);
// 绘制一个渐变圆环(趣味效果)
const gradient = ctx.createLinearGradient(-120, -120, 120, 120);
gradient.addColorStop(0, '#ff4d4d');
gradient.addColorStop(0.2, '#ffa64d');
gradient.addColorStop(0.4, '#ffff4d');
gradient.addColorStop(0.6, '#4dff4d');
gradient.addColorStop(0.8, '#4dd2ff');
gradient.addColorStop(1, '#bf4dff');
ctx.beginPath();
ctx.arc(0, 0, 150, 0, Math.PI * 2);
ctx.fillStyle = gradient;
ctx.fill();
// 加一个内圈白色高光
ctx.beginPath();
ctx.arc(0, 0, 90, 0, Math.PI * 2);
ctx.fillStyle = '#ffffff80';
ctx.fill();
// 最中心的小圆
ctx.beginPath();
ctx.arc(0, 0, 40, 0, Math.PI * 2);
ctx.fillStyle = '#ffcc33';
ctx.fill();
ctx.restore();
// 角度递增,产生旋转
angle += 0.02;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
最短版本(一个跳动的小球,20行代码):
<canvas id="c" width="400" height="400"></canvas>
<script>
const c = document.getElementById('c'), ctx = c.getContext('2d');
let r = 30, growing = true;
function draw() {
ctx.fillStyle = '#0a2f3a';
ctx.fillRect(0, 0, 400, 400);
ctx.beginPath();
ctx.arc(200, 200, r, 0, Math.PI*2);
ctx.fillStyle = '#ff8c5a';
ctx.fill();
r = growing ? r+1 : r-1;
if (r > 80) growing = false;
if (r < 20) growing = true;
requestAnimationFrame(draw);
}
draw();
</script>
更多推荐


所有评论(0)