Canvas多图形脉冲动画实现:已完成圆形效果,需扩展至其他图形
嘿,恭喜你已经搞定圆形的脉冲动画啦!把这个效果扩展到其他图形其实思路超一致——核心就是用三角函数(就像你用的Math.cos())动态调整图形的关键尺寸/属性,让它产生缩放的脉冲感。下面给你几种常见图形的实现方法和代码示例:
通用核心思路
和你实现圆形的逻辑完全相通:
- 用一个持续递增的
angle变量(或者时间戳)来驱动动画循环 - 通过
Math.cos()/Math.sin()生成周期性变化的缩放因子,让尺寸在基础值附近波动 - 将缩放因子应用到图形的关键属性上(比如矩形的宽高、多边形的顶点距离等)
1. 矩形脉冲动画
矩形的关键是动态改变宽高,同时要让它以中心为基准缩放,避免偏移:
function drawRect() { // 填充背景,清空上一帧 context.fillStyle = "#EEEEEE"; context.fillRect(0, 0, canvas.width, canvas.height); // 计算缩放因子:范围在0.5到1.5之间,可调整数值改变脉冲幅度 const scale = 0.5 + Math.abs(Math.cos(angle)); const baseWidth = 50; const baseHeight = 50; // 基于中心定位,所以要减去缩放后尺寸的一半 const x = 100 - (baseWidth * scale) / 2; const y = 25 - (baseHeight * scale) / 2; // 绘制脉冲矩形 context.fillStyle = "#006699"; context.fillRect(x, y, baseWidth * scale, baseHeight * scale); // 更新角度,驱动下一帧 angle += 0.05; }
2. 三角形脉冲动画
三角形可以通过动态调整顶点到中心的距离来实现整体脉冲:
function drawTriangle() { context.fillStyle = "#EEEEEE"; context.fillRect(0, 0, canvas.width, canvas.height); const scale = 0.5 + Math.abs(Math.cos(angle)); const centerX = 175; const centerY = 25; const baseRadius = 30; // 基础外接圆半径,控制三角形大小 context.beginPath(); // 用极坐标转笛卡尔坐标生成三个顶点,同时应用缩放 context.moveTo( centerX + baseRadius * scale * Math.cos(0), centerY + baseRadius * scale * Math.sin(0) ); context.lineTo( centerX + baseRadius * scale * Math.cos(Math.PI * 2/3), centerY + baseRadius * scale * Math.sin(Math.PI * 2/3) ); context.lineTo( centerX + baseRadius * scale * Math.cos(Math.PI * 4/3), centerY + baseRadius * scale * Math.sin(Math.PI * 4/3) ); context.closePath(); context.fillStyle = "#006699"; context.fill(); angle += 0.05; }
3. 自定义多边形脉冲动画
任意多边形的实现思路和三角形一致,通过循环生成带缩放的顶点即可:
function drawPolygon(sides = 6) { context.fillStyle = "#EEEEEE"; context.fillRect(0, 0, canvas.width, canvas.height); const scale = 0.5 + Math.abs(Math.cos(angle)); const centerX = 250; const centerY = 25; const baseRadius = 30; // 基础外接圆半径 context.beginPath(); for (let i = 0; i < sides; i++) { const angleStep = (Math.PI * 2) / sides; // 每个顶点的角度间隔 const x = centerX + baseRadius * scale * Math.cos(i * angleStep); const y = centerY + baseRadius * scale * Math.sin(i * angleStep); i === 0 ? context.moveTo(x, y) : context.lineTo(x, y); } context.closePath(); context.fillStyle = "#006699"; context.fill(); angle += 0.05; }
额外优化技巧
- 统一动画驱动:建议把
angle的更新放到全局的requestAnimationFrame循环里,不要在每个绘制函数里单独更新,这样所有图形的动画节奏会保持一致。 - 调整脉冲强度:修改缩放因子的范围(比如
0.3 + Math.abs(Math.cos(angle)))或者Math.cos()的乘数(比如你圆形里的20),可以控制脉冲的强弱幅度。 - 颜色脉冲拓展:除了尺寸,还可以用三角函数动态调整颜色透明度,比如:
const alpha = 0.5 + 0.5 * Math.cos(angle); context.fillStyle = `rgba(0, 102, 153, ${alpha})`;
内容的提问来源于stack exchange,提问作者Shannon
相关产品推荐
相关产品推荐

