Search code examples
d3.jscanvaschartsd3fc

Button click clears canvas unexpectedly


I try to add new charts to canvas on button click. When I call function addChart directly everything is working good. But when I'm calling the same method on button click the canvas clears and only one chart appears. Please could you help me to understand what's going on?.

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;

I expect that new chart is added on button click but also old charts are visible, but only one chart is visible


Solution

  • Your canvas is auto-cleared, you'll have to set the preserveDrawingBuffer context attribute to true to ensure that your calls to addChart accumulate.