drawkcaB | Backward Compatible logo

rants and tips about software

Creating Checkbox or Toggle button with EaselJS (CreateJS)

Creating a checkbox is rather simple, but here's some code that you can use in your project without having to invent it yourself.

For checkbox or toggle button we need two images representing the states: checked/unchecked, on/off, yes/no, etc. You need to prepare those two images and load them into a createjs.Bitmap. In the game I'm creating, I used these two images:

Of course, you can place both images in a single file and then use sourceRect property to create two bitmaps. The code would go like this:

var imageUnchecked = new createjs.Bitmap('checkboxen.jpg');
imageUnchecked.sourceRect = new createjs.Rectangle(0, 0, 34, 29);

var imageChecked = new createjs.Bitmap('checkboxen.jpg');
imageChecked.sourceRect = new createjs.Rectangle(34, 0, 34, 29);

Now that we have both images, lets create a checkbox. All you need is a simple function call:

var xPos = 100;
var yPos = 100;
var initialState = true;    // checked initially
var btn = new toggleButton(xPos, yPos, imageChecked, imageUnchecked,
    initialState, function(isChecked) {

    if (isChecked)
        // do something
    else
        // do something else

});

To read the state later, outside of click handler, use the following code:

if (btn.checked)
{
    // ...
}

Of course, for this to work, you need toggleButton function. Here it is:

function toggleButton(x, y, checkedImg, uncheckedImg, initialState, onClick)
{
    var self = this;
    self.checked = initialState;

    checkedImg.x = x;
    checkedImg.y = y;
    checkedImg.visible = initialState;
    checkedImg.cursor = 'pointer';

    uncheckedImg.x = x;
    uncheckedImg.y = y;
    uncheckedImg.visible = !initialState;
    uncheckedImg.cursor = 'pointer';

    var checkClick = function(newState) {
        self.checked = newState;
        uncheckedImg.visible = !newState;
        checkedImg.visible = newState;
        onClick(newState);
    };

    checkedImg  .addEventListener('click', function() { checkClick(false); });
    uncheckedImg.addEventListener('click', function() { checkClick(true); });
}

The code above is public domain. Feel free to use and modify it.

Milan Babuškov, 2013-07-11
Copyright © Milan Babu┼íkov 2006-2017