h5实现靶标
实现靶标的基本思路
在H5中实现靶标效果通常涉及使用Canvas或SVG绘制图形,结合JavaScript实现交互逻辑。靶标的核心元素包括同心圆、计分区域以及点击事件响应。
使用Canvas绘制靶标
Canvas是HTML5提供的绘图API,适合动态图形和游戏开发。以下是一个简单的靶标绘制代码示例:
const canvas = document.getElementById('targetCanvas');
const ctx = canvas.getContext('2d');
function drawTarget() {
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const maxRadius = Math.min(centerX, centerY) * 0.8;
// 绘制同心圆(从外到内)
const colors = ['#333', '#fff', '#333', '#fff', '#f00'];
for (let i = 5; i > 0; i--) {
ctx.beginPath();
ctx.arc(centerX, centerY, maxRadius * (i/5), 0, 2 * Math.PI);
ctx.fillStyle = colors[i-1];
ctx.fill();
}
}
添加交互逻辑
通过监听点击事件计算得分,靶标通常从中心向外分数递减:
canvas.addEventListener('click', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const distance = Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2));
const maxRadius = Math.min(centerX, centerY) * 0.8;
// 根据距离计算得分(5环到1环)
const score = Math.max(0, 5 - Math.floor(distance / (maxRadius / 5)));
console.log(`得分: ${score}`);
});
使用CSS3实现简单靶标
若无需复杂交互,纯CSS也能实现静态靶标效果:
<div class="target">
<div class="ring red"></div>
<div class="ring white"></div>
<div class="ring black"></div>
<div class="ring white"></div>
<div class="ring black"></div>
</div>
<style>
.target {
position: relative;
width: 300px;
height: 300px;
}
.ring {
position: absolute;
border-radius: 50%;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
.red {
width: 60px; height: 60px;
background: #f00; z-index: 5;
}
.white {
width: 120px; height: 120px;
background: #fff; z-index: 4;
}
.black {
width: 180px; height: 180px;
background: #333; z-index: 3;
}
/* 更多环样式... */
</style>
性能优化建议
对于移动端或复杂场景,建议以下优化:
- 使用
requestAnimationFrame实现动画 - 离屏Canvas预渲染静态元素
- 避免频繁的DOM操作(CSS方案中减少嵌套层级)
扩展功能方向
可根据需求扩展以下功能:
- 添加动画效果(如命中后的粒子特效)
- 多靶标随机生成
- 数据持久化(记录最高分)
- 响应式设计适配不同屏幕
以上方案可根据项目需求组合使用,Canvas适合高性能游戏场景,CSS方案适合简单展示型需求。

