使用canvas画一个仪表盘
使用 HTML5 的 `<canvas>` 元素可以绘制一个简单的仪表盘。下面是一个基本的示例,展示了如何使用 Canvas API 绘制一个仪表盘,包括刻度和指针。
### HTML 结构
```html
<canvas id="dashboard" width="400" height="400"></canvas>
<script src="dashboard.js"></script>
```
### JavaScript 代码
```javascript
// dashboard.js
const canvas = document.getElementById('dashboard');
const ctx = canvas.getContext('2d');
// 绘制仪表盘背景
function drawDashboard() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 圆形背景
ctx.beginPath();
ctx.arc(200, 200, 150, 0, Math.PI * 2);
ctx.fillStyle = '#eee';
ctx.fill();
ctx.stroke();
// 刻度
for (let i = 0; i < 12; i++) {
const angle = (i * Math.PI) / 6; // 每个刻度间隔 30 度
const x1 = 200 + Math.cos(angle) * 130; // 刻度外圈
const y1 = 200 + Math.sin(angle) * 130;
const x2 = 200 + Math.cos(angle) * 150; // 刻度内圈
const y2 = 200 + Math.sin(angle) * 150;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
使用 HTML5 的 `<canvas>` 元素可以绘制一个简单的仪表盘。下面是一个基本的示例,展示了如何使用 Canvas API 绘制一个仪表盘,包括刻度和指针。
### HTML 结构
```html
<canvas id="dashboard" width="400" height="400"></canvas>
<script src="dashboard.js"></script>
```
### JavaScript 代码
```javascript
// dashboard.js
const canvas = document.getElementById('dashboard');
const ctx = canvas.getContext('2d');
// 绘制仪表盘背景
function drawDashboard() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 圆形背景
ctx.beginPath();
ctx.arc(200, 200, 150, 0, Math.PI * 2);
ctx.fillStyle = '#eee';
ctx.fill();
ctx.stroke();
// 刻度
for (let i = 0; i < 12; i++) {
const angle = (i * Math.PI) / 6; // 每个刻度间隔 30 度
const x1 = 200 + Math.cos(angle) * 130; // 刻度外圈
const y1 = 200 + Math.sin(angle) * 130;
const x2 = 200 + Math.cos(angle) * 150; // 刻度内圈
const y2 = 200 + Math.sin(angle) * 150;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
展开
7
4