mcpskills.net
技能MCP智能体提示词
mcpskills.net — A curated directory of AI agent Skills and MCP servers
TermsPrivacy
← 返回技能
Creative

Canvas 设计

创建基于 Canvas 的交互式设计和可视化。当用户需要 HTML5 Canvas 应用程序、交互式图形、数据可视化或创意编码项目时使用。

作者:Anthropic仓库 →来源 →

使用 HTML5 Canvas API 创建基于画布的交互式设计和可视化。

Canvas 基础

设置

<canvas id="myCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
</script>

基本图形绘制

图形:

// 矩形
ctx.fillRect(x, y, width, height);
ctx.strokeRect(x, y, width, height);

// 圆形
ctx.beginPath();
ctx.arc(x, y, radius, startAngle, endAngle);
ctx.fill();

// 线条
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();

颜色与样式:

ctx.fillStyle = '#ff0000';
ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
ctx.lineWidth = 2;
ctx.globalAlpha = 0.8;

交互模式

动画循环

function animate() {
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 更新状态
  // 绘制对象
  
  requestAnimationFrame(animate);
}
animate();

鼠标交互

canvas.addEventListener('click', (e) => {
  const rect = canvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;
  // 处理点击
});

canvas.addEventListener('mousemove', (e) => {
  // 跟踪鼠标位置
});

高级技术

粒子系统

class Particle {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.vx = (Math.random() - 0.5) * 2;
    this.vy = (Math.random() - 0.5) * 2;
    this.life = 1;
  }
  
  update() {
    this.x += this.vx;
    this.y += this.vy;
    this.life -= 0.01;
  }
  
  draw(ctx) {
    ctx.globalAlpha = this.life;
    ctx.fillRect(this.x, this.y, 2, 2);
  }
}

数据可视化

function drawBarChart(data, x, y, width, height) {
  const barWidth = width / data.length;
  const maxValue = Math.max(...data);
  
  data.forEach((value, i) => {
    const barHeight = (value / maxValue) * height;
    ctx.fillRect(
      x + i * barWidth,
      y + height - barHeight,
      barWidth - 2,
      barHeight
    );
  });
}

最佳实践

  • 使用 requestAnimationFrame 实现流畅动画
  • 仅重绘变化的部分以优化性能
  • 使用图层处理复杂场景(多个画布)
  • 正确清理事件监听器
  • 考虑移动设备的性能
  • 使用离屏画布进行预渲染