How To Change Line Width Using Slider In HTML5 Canvas

JavaScript

29/05/2021


A slider is one of those cool must-have features of any drawing app. And it's surprisingly easy to implement! Let's start off with a simple slider and some configuration.

HTML
<input type="range" min="1" max="10" value="2" />

Be sure to set the default value of lineWidth equals to that of the slider. In our example, that would be 2.

Whenever the user moves the slider, we want to update the canvas property lineWidth. For this, we attach a custom function to the onchange event attribute.

HTML
<input onchange='changeWidth(this.value)' type="range" min="1" max="10" value="2" />

We get the new value by explicitly passing in this.value. The function itself is pretty straightforward.

JAVASCRIPT
const changeWidth = value => context.lineWidth = value

Once again, check out my Codepen for the whole thing in action!


WRITTEN BY

Code and stuff