2. 使用Javascript画多个直方图,该直方图为16个矩形组成,高度设置为随机值,并添加文字图例。
时间: 2024-10-09 19:07:51 浏览: 111
在JavaScript中,你可以使用HTML5的Canvas API来绘制直方图。首先,你需要创建一个canvas元素并获取其绘图上下文。然后,可以按照以下步骤操作:
1. **初始化 canvas**:
```html
<canvas id="histogramCanvas" width="400" height="400"></canvas>
```
2. **获取 canvas 绘图上下文**:
```javascript
const canvas = document.getElementById('histogramCanvas');
const ctx = canvas.getContext('2d');
```
3. **生成16个随机高度**:
```javascript
const randomHeights = Array.from({ length: 16 }, () => Math.floor(Math.random() * 100) + 1); // 高度范围0到100
```
4. **计算矩形的宽度和间距**:
```javascript
const rectWidth = Math.floor(canvas.width / 16);
const barGap = rectWidth;
```
5. **循环绘制每个矩形**:
```javascript
for (let i = 0; i < 16; i++) {
let x = i * (rectWidth + barGap);
let y = canvas.height - randomHeights[i];
ctx.fillStyle = 'rgba(0, 0, 255, 0.8)'; // 蓝色填充
ctx.fillRect(x, y, rectWidth, randomHeights[i]);
}
```
6. **添加文字图例**:
```javascript
const legendText = ['1', '2', '3', ...]; // 图例文本数组
const legendX = canvas.width - 100; // 图例位置
const fontSize = 14;
ctx.font = `${fontSize}px Arial`;
ctx.textAlign = 'center';
legendText.forEach((text, index) => {
ctx.fillText(text, legendX - (index * (rectWidth + barGap) + rectWidth / 2), canvas.height - fontSize);
});
```
7. **显示最终图形**:
```javascript
canvas.style.display = 'block';
```
完整示例代码可能会放在一个函数里,以便复用:
```javascript
function drawHistogram() {
// ...
}
// 初始化时调用
drawHistogram();
```
阅读全文
相关推荐

















