Question

I'd like to find the cheapest (CPU-wise) way to draw arbitrary-length and -width lines in HTML/CSS/Js. I have a case where my page will render 50-200 lines of this kind on a page in addition to other HTML elements. Approaches that have occured to me are:

  • SVG. One for a horizontal line, one for a vertical one. Use Javascript to inject and render them by parameters.
  • Canvas. One canvas that covers the entire screen with transparent background.
  • DIV-tags with border-left/border-top. Abstract through Javascript-methods.

Other suggestions? Which one would perform best? Any compatibility issues with either of these approaches?

Was it helpful?

Solution

Quoted from HTML5 Canvas vs. SVG vs. div

  • SVG is probably better for applications and apps with few items (less than 1000? Depends really)
  • Canvas is better for thousands of objects and careful manipulation, but a lot more code (or a library) is needed to get it off the ground.
  • HTML Divs are clunky and do not scale, making a circle is only possible with rounded corners, making complex shapes is possible but involves hundreds of tiny tiny pixel-wide divs. Madness ensues.

A lot of DOM objects(thousands range) with events attached is going to be very painful for some machines to handle. Since it's only 200 here, it may not be a problem. Still performance increases when using canvas over SVG and over compositing images using the DOM.

OTHER TIPS

For 200 lines? I wouldn't worry about the CPU all that much. This isn't like you're rendering a First Person Shooter or anything.

It depends on context, of course, but the default thought is to use the borders on divs.

If, on the other hand, this is one visual object that can stand on its own, an SVG makes a lot of sense as it is, after all, an image format.

There are a lot of libraries out there for manipulating SVG in the browser. Here's but one: http://snapsvg.io/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top