首页 > 解决方案 > 如何在反应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 错误。我犯了什么错误?

标签: javascripthtmlreactjs

解决方案


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);

工作演示


推荐阅读