用canvas画折线图并且有鼠标hover显示值
时间: 2024-03-07 18:48:26 浏览: 41
下面是用Canvas实现折线图并且有鼠标hover显示值的示例代码:
HTML代码:
```html
<canvas id="canvas" width="400" height="300"></canvas>
```
JavaScript代码:
```javascript
// 获取Canvas元素
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 数据
const data = [10, 20, 30, 40, 50, 60, 70];
// 绘制折线图
ctx.beginPath();
ctx.moveTo(0, canvas.height - data[0]);
for (let i = 1; i < data.length; i++) {
const x = canvas.width * i / data.length;
const y = canvas.height - data[i];
ctx.lineTo(x, y);
}
ctx.stroke();
// 鼠标hover事件
canvas.addEventListener('mousemove', function (event) {
// 获取Canvas元素的尺寸
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
// 获取鼠标位置相对于Canvas元素的坐标
const x = (event.clientX - rect.left) * scaleX;
const y = (event.clientY - rect.top) * scaleY;
// 判断鼠标位置是否在折线图上
const index = Math.floor(x / (canvas.width / data.length));
if (index >= 0 && index < data.length) {
// 显示值
const value = data[index];
ctx.font = '14px Arial';
ctx.fillStyle = '#000';
ctx.fillText(value, x, canvas.height - value - 10);
}
});
```
在上述代码中,我们先通过`moveTo()`和`lineTo()`方法绘制了折线图,然后在鼠标移动事件的回调函数中判断鼠标位置是否在折线图上,并在鼠标位置上显示对应的数据值。
需要注意的是,在显示数据值时,我们可以使用`fillText()`方法将数据值绘制在Canvas中,但是需要注意数据值的位置和字体、颜色等属性的设置。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)