单击按钮会意外清除画布

问题描述 投票:0回答:1

我尝试在单击按钮时将新图表添加到画布。当我直接调用函数

addChart
时,一切正常。但是,当我在按钮上调用相同的方法时,单击画布会清除,并且只显示一张图表。请您帮我了解发生了什么事吗?.

index.html

<html>
<head>
    <script src="//unpkg.com/[email protected]/dist/d3.min.js"></script>
    <script src="//unpkg.com/[email protected]/build/d3fc.js"></script>
</head>

<body>
<button id="#button">Add Chart</button>
<canvas id="line-webgl"></canvas>

<script src="/src/chart3.js" type="module"></script>

</body>

</html>

chart3.js

const width = 500, height = 250;

const xScale = d3.scaleLinear()
    .domain([0, 50])
    .range([0, width]);

const yScale = d3.scaleLinear()
    .domain([0, 1])
    .range([height, 0]);

const canvasgl = d3.select('#line-webgl').node();

canvasgl.width = width;
canvasgl.height = height;
const gl = canvasgl.getContext('webgl');

// the webgl series component that renders data, transformed
// using D3 scales, onto a WebGL context
const webglLine = fc.seriesWebglLine()
    .xScale(xScale)
    .yScale(yScale)
    .crossValue((_, i) => i)
    .mainValue(d => d)
    .context(gl);

export const addChart = () => {
    const data = d3.range(0, 50).map(d => Math.random());
    webglLine(data);
}

addChart();
addChart();
addChart();

/* somehow clears canvas on click, only one chart is drawing */
document.getElementById('#button').onclick = addChart;

我希望在单击按钮时添加新图表,但旧图表也可见,但只有一个图表可见

d3.js canvas charts webgl d3fc
1个回答
0
投票

理解 Javascript 中的

Global Scope
Function Scope
非常重要。

// THESE FUNCTION CALLS ARE IN SAME SCOPE

addChart();
addChart();
addChart();

/// BUT THIS FUNCTION CREATE NEW FUNCTION SCOPE WHEN IT IS CALLED
document.getElementById('#button').onclick = addChart;

// LIKE THIS
() => {
  addChart();
}
...

在全局范围内调用

addChart()
的结果可以累积在画布上,但是当您单击按钮时,它会创建新的函数范围,因此所有变量都被声明为新的。

© www.soinside.com 2019 - 2024. All rights reserved.