Why I no longer use D3.js

When we set the attributes width and height it may look like we’re setting the CSS size, but we’re actually setting the size of the canvas drawing space..These are not the same thing.Canvas with a drawing space of 50×50 pixels, but stretched to 200×200 CSS pixels, causing pixelation.Normally your CSS pixels would be set to the same size as your canvas drawing space, but when you zoom in/out with your browser, you’ll see the same issue again..The solution is to use window.devicePixelRatio and scale your canvas drawing space.onResize() { let canvas = this.base.querySelector('canvas'); let ctx = canvas.getContext('2d'); let PIXEL_RATIO = window.devicePixelRatio; canvas.width = canvas.offsetWidth * PIXEL_RATIO; canvas.height = canvas.offsetHeight * PIXEL_RATIO; ctx.setTransform(PIXEL_RATIO, 0, 0, PIXEL_RATIO, 0, 0); this.props.onDraw(ctx, canvas.offsetWidth, canvas.offsetHeight);}Source: JSFiddleUsing the pixel ratio, we can increase the drawing space for the canvas..But increasing the drawing space isn’t enough, we also need to tell the canvas that future drawing operations must be scaled to the pixel ratio..This will then solve all of the scaling problems.Can you tell which ones are canvas, and which ones are SVG?Zoomed in browser, with a standard canvas, a pixel ratio aware canvas, and SVG.ConclusionAs you can see, there’s numerous reasons as to why D3 is fairly outdated now for many common use cases..The web has evolved significantly since its release..If you’re doing simple charts like donuts, bar charts, line charts, scatter plots, etc, consider seeing if you can implement them using your existing framework..There’s nothing really that D3 will provide you for those use cases..In terms of maintenance, your code will likely be more maintainable rather than more difficult to maintain, and if you need to make any changes, it should be trivial to make those changes.There’s no reason for product managers to feel concerned about not using D3, and you shouldn’t be concerned either.Thanks for reading!Updates[17th December 2018] Article updated to add “But Canvas doesn’t scale like SVG?” section.. More details

Leave a Reply