Js实现冰墩墩
使用Canvas绘制冰墩墩
在JavaScript中,可以通过Canvas API绘制冰墩墩形象。以下是实现的基本代码框架:
const canvas = document.getElementById('bingDwenDwen');
const ctx = canvas.getContext('2d');
// 绘制头部轮廓
ctx.beginPath();
ctx.arc(250, 150, 100, 0, Math.PI * 2);
ctx.fillStyle = '#ffffff';
ctx.fill();
// 绘制黑色眼圈
ctx.beginPath();
ctx.ellipse(200, 130, 30, 40, 0, 0, Math.PI * 2);
ctx.ellipse(300, 130, 30, 40, 0, 0, Math.PI * 2);
ctx.fillStyle = '#000000';
ctx.fill();
// 绘制彩色光环
const gradient = ctx.createLinearGradient(150, 50, 350, 50);
gradient.addColorStop(0, '#ff0000');
gradient.addColorStop(0.5, '#00ff00');
gradient.addColorStop(1, '#0000ff');
ctx.beginPath();
ctx.arc(250, 150, 110, 0, Math.PI * 2);
ctx.strokeStyle = gradient;
ctx.lineWidth = 5;
ctx.stroke();
使用SVG实现方案
SVG方案更适合需要缩放而不失真的场景:
<svg width="500" height="500" viewBox="0 0 500 500">
<!-- 头部 -->
<circle cx="250" cy="150" r="100" fill="white" stroke="black" stroke-width="2"/>
<!-- 眼睛 -->
<ellipse cx="200" cy="130" rx="30" ry="40" fill="black"/>
<ellipse cx="300" cy="130" rx="30" ry="40" fill="black"/>
<!-- 彩色光环 -->
<defs>
<linearGradient id="rainbow" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="red"/>
<stop offset="50%" stop-color="green"/>
<stop offset="100%" stop-color="blue"/>
</linearGradient>
</defs>
<circle cx="250" cy="150" r="110" fill="none" stroke="url(#rainbow)" stroke-width="5"/>
</svg>
使用CSS绘制简化版
纯CSS方案适合简单展示需求:
<style>
.bingdwendwen {
position: relative;
width: 200px;
height: 200px;
background: white;
border-radius: 50%;
border: 2px solid black;
}
.eye {
position: absolute;
width: 60px;
height: 80px;
background: black;
border-radius: 50%;
top: 30px;
}
.eye.left { left: 40px; }
.eye.right { right: 40px; }
.rainbow {
position: absolute;
width: 220px;
height: 220px;
border-radius: 50%;
border: 5px solid transparent;
border-image: linear-gradient(to right, red, green, blue);
border-image-slice: 1;
top: -10px;
left: -10px;
}
</style>
<div class="bingdwendwen">
<div class="eye left"></div>
<div class="eye right"></div>
<div class="rainbow"></div>
</div>
实现动画效果
为冰墩墩添加简单的动画效果:
// 旋转彩虹光环
function animateHalo() {
let rotation = 0;
setInterval(() => {
rotation = (rotation + 1) % 360;
canvas.style.transform = `rotate(${rotation}deg)`;
}, 50);
}
// 眨眼动画
function blinkEyes() {
setInterval(() => {
ctx.clearRect(170, 90, 60, 80);
ctx.clearRect(270, 90, 60, 80);
// 绘制闭眼状态
ctx.fillRect(180, 130, 40, 5);
ctx.fillRect(280, 130, 40, 5);
setTimeout(() => {
// 恢复睁眼状态
ctx.clearRect(170, 90, 60, 80);
ctx.clearRect(270, 90, 60, 80);
ctx.beginPath();
ctx.ellipse(200, 130, 30, 40, 0, 0, Math.PI * 2);
ctx.ellipse(300, 130, 30, 40, 0, 0, Math.PI * 2);
ctx.fill();
}, 200);
}, 3000);
}
响应式调整
确保绘制效果适应不同屏幕尺寸:
function resizeCanvas() {
const container = document.getElementById('container');
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
drawBingDwenDwen();
}
window.addEventListener('resize', resizeCanvas);
这些实现方案可以根据具体需求进行组合或扩展,建议从简单的SVG方案开始,逐步增加细节和交互功能。



