Recently I have been working on a problem with SVG & the HTML5 Canvas that causes bad looking output in some of our files. It was first brought to our attention by a client.
Here is the test file I was using, it was made in OpenOffice and exported as a PDF document (OpenOffice is one of the tools that creates nicely structured PDFs)
Here you can see the SVG output on my test file.
And here you can see the HTML canvas output (notice it’s much more easy to identify that there’s a problem).
What we have here is a problem with how SVG and the Canvas interpret their grid system. An image consists of an array of pixels with different attributes, or in the case of vector images, a set of equations that can be used to describe what pixels should look like at any given size. The pixels themselves are treated as indivisible units, so you can’t have half a pixel. However in SVG and HTML5’s Canvas the grid allows for floating point positions. This in itself, causes you to run into issues when wanting to draw pixel perfect graphics using these technologies as their grid treats coordinates like this:
The green square represents a pixel and it’s coordinates are actually: 0.5, 2.5 on canvas and SVG. In other situations and programs you would expect the coordinate of said pixel to be: 0, 2
So the canvas treats pixels as points and lets you place them with ‘infinite’ precision but this means placing them at point 0, 2 would result in the point overlapping 4 pixels; so it averages the colour of the pixel across all 4. This results in the blurry lines you can see in my examples.
A good diagram of this effect can be found in the Canvas tutorial provided on Mozillas website:
The client who pointed out the problem proposed the solution of adding 0.5 to each of our coordinates, which improved the look of the file in question, but causes problems in other cases because of fractional line lengths. Which in turn means we need to re-factor some more of our code. All in all this issue has caused much confusion among us and other developers but I can see why they choose to use such a coordinate system, it just means you need to take extra care when planning to use the canvas for pixel perfect shapes and lines. What do you think of the canvas and SVG coordinate system?
This post is part of our “SVG Article Index” in these articles, we aim to help you build knowledge and understand SVG.
Latest posts by Lyndon Armitage (see all)
- It’s as Easy as Pi to make MagPi into HTML5 on your Pi - October 9, 2013
- Making a jQuery PDF Viewer - August 20, 2013
- Check if a PDF is valid using the HTML5 File API - July 11, 2013
- Save time, Test your Code Part 2 - June 26, 2013
- Save time, Test your Code Part 1 - June 18, 2013