js实现笑脸
使用Canvas绘制笑脸
在HTML中创建Canvas元素,通过JavaScript绘制笑脸。以下代码展示如何绘制一个简单的笑脸:
<canvas id="smileCanvas" width="200" height="200"></canvas>
<script>
const canvas = document.getElementById('smileCanvas');
const ctx = canvas.getContext('2d');
// 绘制黄色圆形脸部
ctx.beginPath();
ctx.arc(100, 100, 80, 0, Math.PI * 2);
ctx.fillStyle = 'yellow';
ctx.fill();
ctx.strokeStyle = 'black';
ctx.stroke();
// 绘制左眼
ctx.beginPath();
ctx.arc(70, 70, 10, 0, Math.PI * 2);
ctx.fillStyle = 'black';
ctx.fill();
// 绘制右眼
ctx.beginPath();
ctx.arc(130, 70, 10, 0, Math.PI * 2);
ctx.fill();
// 绘制微笑的嘴
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI);
ctx.stroke();
</script>
使用SVG创建笑脸
通过SVG矢量图形实现笑脸,适合需要缩放而不失真的场景:
<svg width="200" height="200" viewBox="0 0 200 200">
<!-- 脸部 -->
<circle cx="100" cy="100" r="80" fill="yellow" stroke="black" stroke-width="2"/>
<!-- 左眼 -->
<circle cx="70" cy="70" r="10" fill="black"/>
<!-- 右眼 -->
<circle cx="130" cy="70" r="10" fill="black"/>
<!-- 微笑嘴 -->
<path d="M60 120 Q100 170 140 120" fill="none" stroke="black" stroke-width="3"/>
</svg>
使用CSS和HTML创建笑脸
纯CSS实现的笑脸,无需JavaScript:
<div class="smiley-face">
<div class="eye left-eye"></div>
<div class="eye right-eye"></div>
<div class="smile"></div>
</div>
<style>
.smiley-face {
width: 200px;
height: 200px;
background: yellow;
border-radius: 50%;
border: 3px solid black;
position: relative;
}
.eye {
width: 20px;
height: 20px;
background: black;
border-radius: 50%;
position: absolute;
top: 50px;
}
.left-eye { left: 50px; }
.right-eye { right: 50px; }
.smile {
width: 100px;
height: 50px;
border: 3px solid black;
border-color: transparent transparent black transparent;
border-radius: 0 0 50px 50px;
position: absolute;
bottom: 40px;
left: 50px;
}
</style>
使用Emoji表情符号
最简单的实现方式,直接使用Unicode表情符号:
console.log('😊'); // 简单笑脸
console.log('😀'); // 大笑脸
console.log('😂'); // 笑哭脸
动画笑脸实现
通过CSS动画让笑脸动起来:

<div class="animated-smiley">😊</div>
<style>
.animated-smiley {
font-size: 100px;
display: inline-block;
animation: smileyAnimation 2s infinite;
}
@keyframes smileyAnimation {
0% { transform: scale(1); }
50% { transform: scale(1.2); }
100% { transform: scale(1); }
}
</style>
每种方法适用于不同场景,Canvas适合需要动态绘制的场景,SVG适合矢量图形需求,CSS方法适合轻量级实现,而Emoji则是最快捷的解决方案。






