如何制作可交互的橙色无脸空心头部Alan Becker风格火柴人
Alan Becker风格橙色交互火柴人实现方案
核心需求梳理
- 整体为橙色,无面部特征
- 头部是无填充的空心圆形
- 具备与电脑交互的能力(移动、点击触发动作)
完整实现代码
以下是基于Canvas的完整实现代码,匹配需求样式的同时,添加了键盘控制移动、点击触发交互动作的功能:
<!DOCTYPE html> <html> <head> <title>Alan Becker Style Stick Figure</title> <style> canvas { border: 2px solid #333; background-color: #f0f0f0; } </style> </head> <body> <canvas id="stickFigureCanvas" width="800" height="400"></canvas> <script> const canvas = document.getElementById('stickFigureCanvas'); const ctx = canvas.getContext('2d'); let stickFigureX = 400; // 初始居中X位置 const stickFigureY = 300; // 地面Y位置 const moveSpeed = 5; // 移动速度 let isInteracting = false; // 交互状态标记 // 绘制火柴人函数 function drawStickFigure(x, y, interacting) { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.strokeStyle = '#ff7f24'; // 匹配Alan Becker风格的鲜艳橙色 ctx.lineWidth = 4; // 头部:空心圆形,仅描边无填充 ctx.arc(x, y - 100, 20, 0, Math.PI * 2, true); ctx.stroke(); // 身体线条 ctx.moveTo(x, y - 80); ctx.lineTo(x, y - 10); // 手臂:区分交互/正常状态 if (interacting) { // 交互动作:手臂抬起模拟点击 ctx.moveTo(x, y - 60); ctx.lineTo(x + 30, y - 80); ctx.moveTo(x, y - 60); ctx.lineTo(x - 30, y - 80); } else { // 正常状态:手臂自然下垂 ctx.moveTo(x, y - 60); ctx.lineTo(x - 30, y - 20); ctx.moveTo(x, y - 60); ctx.lineTo(x + 30, y - 20); } // 腿部线条 ctx.moveTo(x, y - 10); ctx.lineTo(x - 25, y); ctx.moveTo(x, y - 10); ctx.lineTo(x + 25, y); ctx.stroke(); } // 键盘控制左右移动 document.addEventListener('keydown', (e) => { if (e.key === 'ArrowLeft' && stickFigureX > 40) { stickFigureX -= moveSpeed; } if (e.key === 'ArrowRight' && stickFigureX < canvas.width - 40) { stickFigureX += moveSpeed; } drawStickFigure(stickFigureX, stickFigureY, isInteracting); }); // 点击画布触发交互动作 canvas.addEventListener('click', () => { isInteracting = !isInteracting; drawStickFigure(stickFigureX, stickFigureY, isInteracting); // 模拟交互后恢复正常姿态 if (isInteracting) { setTimeout(() => { isInteracting = false; drawStickFigure(stickFigureX, stickFigureY, isInteracting); }, 1000); } }); // 初始绘制 drawStickFigure(stickFigureX, stickFigureY, isInteracting); </script> </body> </html>
代码说明
- 样式适配:将描边色改为Alan Becker风格的鲜艳橙色,头部仅执行描边操作,实现空心无面部的要求
- 交互实现:
- 左右方向键控制火柴人在画布内移动
- 点击画布触发火柴人做出交互动作(手臂抬起模拟点击电脑),1秒后自动恢复正常姿态
- 风格还原:保持粗壮线条、简洁动作的特点,匹配Alan Becker标志性的火柴人视觉风格
内容的提问来源于stack exchange,提问作者Ezra Hope




