Using canvas and D3
Until now, we have used D3 to create visualizations by manipulating SVG elements and divs. In some cases, it can be more convenient to render the visualizations using the canvas elements, for performance reasons or if we need to transform and render raster images. In this section, we will learn how to create figures with the HTML5 canvas element and how to use D3 to render figures with the canvas element.
Creating figures with canvas
The HTML canvas element allows you to create raster graphics using JavaScript. It was first introduced in HTML5. It enjoys more widespread support than SVG and can be used as a fallback option. Before diving deeper into integrating canvas and D3, we will construct a small example with canvas.
The canvas element should have the width
and height
attributes. This alone will create an invisible figure of the specified size:
<!— Canvas Element --> <canvas id="canvas-demo" width="650px" height="60px">...