javascript - 如何在反应js中使用用javascript编写的热图
问题描述
我有一个 js 文件,它根据给定的点绘制热图。我希望用 reactjs 完成同样的工作。我该怎么做?
热图.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Heatmap Test Code</title>
<script src='http://www.patrick-wied.at/static/heatmapjs/assets/js/heatmap.min.js'></script>
</head>
<body>
<div id='heatMap' style="height: 742px">
<canvas width="1024" height="742" style="position:absolute; left: 0; top: 0"></canvas>
</div>
</body>
<script>
var heatmapInstance = h337.create({
container: document.getElementById('heatMap')
});
var testData = {
min: 0,
max: 100,
data: [{'x': 948, 'y': 71, 'value': 1}, {'x': 949, 'y': 70, 'value': 1}, {'x': 948, 'y': 69, 'value': 1}, {'x': 946, 'y': 67, 'value': 1}, {'x': 390, 'y': 39, 'value': 1}, {'x': 376, 'y': 39, 'value': 1}, {'x': 288, 'y': 16, 'value': 1}, {'x': 200, 'y': 12, 'value': 1}, {'x': 134, 'y': 12, 'value': 1}, {'x': 96, 'y': 12, 'value': 1}, {'x': 80, 'y': 12, 'value': 1}, {'x': 69, 'y': 15, 'value': 1}, {'x': 65, 'y': 17, 'value': 1}]
};
heatmapInstance.setData(testData);
</script>
</html>
我在 reactjs 中尝试了以下内容:
在 index.html 中:
included the script in index.html (<script src="heatmap.min.js" ></script>)
在 heat.js 中:
export function heat(){
//code to draw heatmap
}
在 app.js 中:
import {heat} from './heat';
class App extends Component {
componentWillMount(){
heat();
}
当我在 reactjs 中运行代码时,它会抛出 h337 is not defined 错误。我犯了什么错误?
解决方案
在npm install heatmap.js
您可以使用以下代码创建基本工作热图之后:
App.js
import React, {useEffect} from "react";
import ReactDOM from "react-dom";
import h337 from "heatmap.js";
import "./styles.css";
function App() {
useEffect(() => {
var heatmapInstance = h337.create({
// only container is required, the rest will be defaults
container: document.querySelector('.App')
});
// now generate some random data
var points = [];
var max = 0;
var width = 840;
var height = 400;
var len = 200;
while (len--) {
var val = Math.floor(Math.random()*100);
max = Math.max(max, val);
var point = {
x: Math.floor(Math.random()*width),
y: Math.floor(Math.random()*height),
value: val
};
points.push(point);
}
// heatmap data format
var data = {
max: max,
data: points
};
// if you have a set of datapoints always use setData instead of addData
// for data initialization
heatmapInstance.setData(data);
})
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
推荐阅读
- python - 带有多个参数的 Django 模板标签过滤器
- ios - iOS UNUserNotificationCenter 关闭通知后一直接收通知
- xcode7 - 如何在 macOS Mojave 版本 10.14.3 上安装 xcode 7 和编辑 Swift 2.X
- concurrency - 在执行数据库读/写的应用程序中实现高并发?
- python - 我不能使用“点子”
- java - 关于多态性的代码段。为什么以下会导致编译错误?
- sql-server - 将 11 小时添加到 SQL Server 中的 datetime2 列
- ruby-on-rails - RSPEC 中的存根 JSON.parse
- vue.js - 在 VueJS 中拖放
- css - 如何确定我的 CSS 选择器从哪里被覆盖?时间线.js