Sunday, 27 July 2014

Building a drawing app with HTML5's canvas (Part 4)


In this part of the series, we'll build a little radius indicator and two buttons to increase and decrease the value of our radius variable which effectively is increasing or decreasing our brush size.


View Code
View Demo

Building the controls

To build a control bar on the top to control stuff like the radius, colour etc. (we'll build colour switching functions in the next parts), we simply create a navbar on top and add some controls to it.

Here's some HTML you might use to create a control bar:
<div class="toolbar">    
    Radius: 
    <span id="radVal">10</span>
    <div id="radPlus" class="button">+</div>
    <div id="radMinus" class="button">-</div> 
</div>

I'm not going to go over styles at all, you can style it however you want, but if you want to use the same styles I used in the demo above, you can click on the "View code" button and use the styles given there.

Changing the radius

We'll add event listeners to the plus and minus buttons that call functions called incRad and decRad that increase or decrease the radius of the brush and also change the value of radius in the span element called radVal.

We'll first have to declare variables that reference the two buttons and the span, then we can add the event listeners.
var plus = document.getElementById("radPlus"),
    minus = document.getElementById("radMinus"),
    val = document.getElementById("radVal");

plus.addEventListener("mousedown", incRad);
minus.addEventListener("mousedown", decRad);

Now we'll define the functions. Well the two functions should simply increase or decrease the radius by using the statements radius++ or radius-- (Note that the radius variable was already declared). And after that change the text on the screen. So the code would look like this:
var incRad = function(e){
    radius++;
    val.innerHTML = radius;
}

var decRad = function(e){
    radius--
    val.innerHTML = radius;
}
But it's a good idea to have a minimum and maximum brush size. Let's just set it to 1 and 100. So, when the user clicks the + button when the brush size is 100 or clicks the - button when the brush size is 1 then we simply don't do anything! So, here's what we write in code:
var incRad = function(e){
    if (radius == 100)
        return;
    radius++;
    val.innerHTML = radius;
}

var decRad = function(e){
    if (radius == 1)
        return;
    radius--
    val.innerHTML = radius;
}

And, we're done!

Here's what our application looks like as of now:
Our app can now change the brush size!


But we've got some things left to do... 

In the next part we'll add a colour palette to the right side of the control bar so that the user can change the colour of the brush as they use the app.

In a later part, we'll also add functionality to save the image to the user's computer.

No comments:

Post a Comment