Lyndon Armitage Lyndon is a general Developer. He has a keen interest in AI and Games Programming and runs a blog that he periodically updates.

# Handling Floating Point coordinates with Pixels in SVG & HTML5 Canvas?

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.

## Are you a Developer working with PDF files?

Our developers guide contains a large number of technical posts to help you understand the PDF file Format.

## Find out more about our software for Developers

Lyndon Armitage Lyndon is a general Developer. He has a keen interest in AI and Games Programming and runs a blog that he periodically updates.