当前位置:首页 > HTML

h5实现靶标

2026-01-12 16:18:48HTML

H5实现靶标的方法

使用Canvas绘制靶标

Canvas是HTML5提供的绘图API,适合绘制复杂的图形如靶标。通过JavaScript控制绘制逻辑,可以实现动态效果。

<canvas id="targetCanvas" width="400" height="400"></canvas>
<script>
  const canvas = document.getElementById('targetCanvas');
  const ctx = canvas.getContext('2d');
  const centerX = canvas.width / 2;
  const centerY = canvas.height / 2;

  function drawTarget() {
    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制同心圆
    const colors = ['red', 'white', 'red', 'white', 'red'];
    const radii = [180, 140, 100, 60, 20];

    for (let i = 0; i < radii.length; i++) {
      ctx.beginPath();
      ctx.arc(centerX, centerY, radii[i], 0, Math.PI * 2);
      ctx.fillStyle = colors[i];
      ctx.fill();
    }
  }

  drawTarget();
</script>

使用CSS实现静态靶标

纯CSS方案适合不需要交互的静态靶标,利用border-radius和渐变实现同心圆效果。

<div class="target">
  <div class="ring red"></div>
  <div class="ring white"></div>
  <div class="ring red"></div>
  <div class="ring white"></div>
  <div class="ring red center"></div>
</div>

<style>
  .target {
    position: relative;
    width: 400px;
    height: 400px;
  }
  .ring {
    position: absolute;
    border-radius: 50%;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  .red { background-color: red; }
  .white { background-color: white; }
  .ring:nth-child(1) { width: 360px; height: 360px; }
  .ring:nth-child(2) { width: 280px; height: 280px; }
  .ring:nth-child(3) { width: 200px; height: 200px; }
  .ring:nth-child(4) { width: 120px; height: 120px; }
  .ring:nth-child(5) { width: 40px; height: 40px; }
</style>

添加交互功能

为Canvas靶标添加点击事件检测,实现打靶交互效果。

canvas.addEventListener('click', (event) => {
  const rect = canvas.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;

  // 计算点击位置与中心的距离
  const distance = Math.sqrt(
    Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2)
  );

  // 根据距离判断得分
  let score = 0;
  if (distance <= 20) score = 10;
  else if (distance <= 60) score = 8;
  else if (distance <= 100) score = 6;
  else if (distance <= 140) score = 4;
  else if (distance <= 180) score = 2;

  alert(`得分: ${score}`);
});

SVG实现方案

SVG作为矢量图形方案,适合需要缩放保持清晰度的场景。

<svg width="400" height="400" viewBox="0 0 400 400">
  <circle cx="200" cy="200" r="180" fill="red"/>
  <circle cx="200" cy="200" r="140" fill="white"/>
  <circle cx="200" cy="200" r="100" fill="red"/>
  <circle cx="200" cy="200" r="60" fill="white"/>
  <circle cx="200" cy="200" r="20" fill="red"/>
</svg>

性能优化建议

对于动态靶标,使用requestAnimationFrame实现动画。避免频繁重绘整个Canvas,只更新变化部分。静态靶标优先考虑CSS或SVG方案。

h5实现靶标

标签: 靶标
分享给朋友: