Drawing on the Web with Canvas Rendering Context

Updated on
html canvas drawing feature image

How would you go about creating a 2D drawing app in the browser?

The html canvas element in combination with the CanvasRenderingContext2D interface provides a simple way to draw graphics on the web.

CanvasRenderingContext2D

The CanvasRenderingContext2D interface provides the 2D rendering context for the drawing surface of a canvas element. It is used to draw shapes, text, images, and other objects on the canvas.

The api has pretty simple methods and is overall easy to use (compared to WebGL for example).

Alternatives

  • WebGL: runs on the GPU and is more complex than the 2D canvas api. Suitable for more complex graphics and animations.

  • SVG: Vector graphics as opposed to raster graphics. SVG is more suitable for scalable graphics.

Use Cases

Some common use cases for the 2D canvas include:

  • Light Photo editing
  • Drawing / sketching apps
  • Simple games

Example App

In this example we have a couple of simple requirements:

  • User can draw lines on the canvas
  • User can set a background
  • User can choose background and line colors from an EyeDropper color picker and default provided color pallette
  • User can clear the canvas
  • User can undo / redo
  • User can download the drawing as an image
  • User can do all of the above with hotkeys

Feature Ideas

You could take this example further by adding more features such as:

Pen customization: a form to allow the user to customize the size and brush stroke of the pen.

Saving image state to a persistent store: the image state is currently stored in component state. You could save the image state to a persistent store such as local storage or a database.

Adding text: add a new action button to allow the user to add text to the canvas. The CanvasRenderingContext2D interface provides strokeText and fillText methods for drawing text on the canvas.

Adding images: allow the user to upload images to the canvas. The CanvasRenderingContext2D interface provides an drawImage method for drawing images on the canvas. This could really open up many possibilities for the app.

Adding a layer system: allow the user to add multiple layers to the canvas. This would allow the user to draw on different layers and toggle the visibility of each layer. This would be a more complex feature to implement but would provide a lot of flexibility to the user.

Fill area: add a new action button to allow the user to fill an area with a color. The CanvasRenderingContext2D interface provides a fill method for filling an area with the current fill style.

Thoughts

Its worth mentioning again that WebGL and SVG are two other interesting options for drawing on the web that are worth looking into.

The MDN docs for the CanvasRenderingContext2D interface are a great resource.

Newsletter