Drawing outline for any kind of HTML Canvas objects

Creating an outline for single basic HTML canvas object is very simple since we are able to use lineWidth property on canvas context. Where as if we need to draw outline for complex object such as combination of basic elements or png image with some transparent portions we have to use another approach.

Pixel level manipulation can be used with context.getImageData() method which gives pixel data (r g b a) of entire canvas

How Masking method Works

Very first I am saving the transparent and non-transparent details to 2D array A.

Thereafter I am using 3x3 mask to detect edges. Mask is sliding over each pixel and if it detects transparent pixel (a = 255) it colors every transparent pixel and also the middle pixel. Then the 2D array B will be constructed with outline details.

Eventually result will be rendered in the HTML canvas.

Source code:

Demo : http://shalithasuranga.me/Canvas-Outlines-Drawing/

Happy Coding!!

Originally published at shalithasuranga.me on January 9, 2018.

Written by

Software Engineer at 99x | Apache PMC member | Open Source Contributor (Author of Neutralinojs) | Technical Writer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store