...

/

Painting on an HTML5 Canvas

Painting on an HTML5 Canvas

The title explains it all. Let's create a paint canvas with a color palette and line thickness options!

We'll cover the following...

This exercise is designed as an on-site interview question, which means you don’t have hours to complete it. Therefore, we will not use heavy templates, Babel, or any tooling.

Exercise:

Create a webpage, where you can paint on a canvas. The user should be able to select the color and the thickness (pixel) of the drawn line. You may use any HTML5 elements.

Solution:

Different browsers render the same elements differently. To combat this problem, the demonstration of using CSS resets or normalizers is beneficial. Resets remove all element styles, while normalizers make the default styles consistent for as many browsers as possible. I chose to use normalize.css. You can get it using

Press + to interact
npm install normalize.css

We can reference this normalizer in our HTML file. Let’s create our index.html file:

Press + to interact
<!doctype html>
<html>
<head>
<title>Paint - zsoltnagy.eu</title>
<link rel="stylesheet"
href="node_modules/normalize.css/normalize.css">
<link rel="stylesheet" href="styles/styles.css">
</head>
<body>
<input type="color" class="js-color-picker color-picker">
<canvas class="js-paint paint-canvas"
width="600"
height="300"></canvas>
</body>
</html>

Save the file as index.html.

The markup contains a color picker, and the canvas element.

Notice that we created a reference to styles/styles.css. Let’s create it, and put some border settings around the canvas for clarity:

Press + to interact
.paint-canvas {
border: 1px black solid;
display: block;
margin: 1rem;
}
.color-picker {
margin: 1rem 1rem 0 1rem;
}

The canvas is now clearly visible, and we can also select the color.

In the JavaScript file, we will first reference our canvas element by selecting the .js-canvas element. Notice I used the .js- prefix in the class in order to make it clear, this class is used for functionality, not for styling. This is separation of concerns in action.

Using a .js- prefixed class in the CSS is discouraged. Imagine a web styler using your .js- class to hack some styles in your application. Then one day, the implementer of a feature decides the .js- class is not needed anymore. Relying on the naming, he deletes the .js- class, breaking the styles. We don’t want these ...