Cocos2d-JS Tutorial – Chalk Board 3 – Drawing Grid Lines

Objective

In Continuation of our last Chalk Board Erasing post, let’s see how to automatically draw Grid lines in this post.

ENGINE VERSION : COCOS2D-JS 3.8.1

Preview

Contents

  1. Prerequisite
  2. Download
  3. Draw a Line
  4. Draw smoother Line
  5. Draw vertical Lines
  6. Draw Grid
  7. Center in Board
  8. Complete Board.js Code

At any point of time, refer to the source files Board.jsmain.js and resource.js for clarity.

1. Prerequisite

See this link to get started with Cocos2d-x.

2. Download Code

Download project @ https://github.com/GethuGames/cocos2dx-chalk-board-draw/archive/grid1.0.zip Complete Project can be found in GITHUB.

Note: This is not directly executable. This contains the source and resources excluding the cocos2dx bundle. So, create a new project, download this github and replace the files in ur new project with this github files to be able to run the project.

3. Draw a Line

Create a class variable `currentLinePercent` and 2 functions, `drawBoard` and `updateDrawLine`.

  1. currentLinePercent:The line will be drawn by a series of dots and this variable determines where the dot should be drawn at any given time. currentLinePercent will start at 1 and gradually decreased to 0 over time in the `update` function.
  2. drawBoard: This function will be invoked from the Class constructor. This will just schedule the other function `updateDrawLine` that has the core logic.
  3. updateDrawLine: This will be invoked in every game cycle. This function will decrement currentLinePercent by a small amount, then calculate the point to be drawn, and call `drawBrushAtPoint()` at that point. This will be repeated till currentLinePercent reaches 0, and hence the line touches the bottom of the screen.
    drawBoard : function() {
        this.currentLinePercent = 1.0;
        this.schedule(this.updateDrawLine);
    },

    updateDrawLine : function(dt) {
        this.currentLinePercent -=  0.02;
        to = cc.p(cc.winSize.width * 0.5, this.currentLinePercent * cc.winSize.height);
        this.drawBrushAtPoint(to, cc.color(250, 250, 50, 200));

        if (this.currentLinePercent < 0.0) {
            this.unschedule(this.updateDrawLine);
        }
    },
  1. Schedule the `updateDrawLine` to be invoked on every game loop.
  2. Line’s Y position is calculated from currentLinePercent,
    1. which is set to 1 in the beginning (= max height, top of the screen)
    2. and decremented to 0 over time (bottom of the screen)
  3. Point to draw is calculated as follows:
    1. X position: the center of the screen
    2. Y position: currentLinePercent * window height
  4. When the currentLinePercent reaches 0, which is the bottom of the screen, unschedule `updateDrawLine` and stop Drawing.

As with the free hand drawing in Part 1, here also, we get gaps between the points. We can interpolate the intermediate points as before. But just for the sake learning/exploration, let’s take another technique.

Line draw - First

4. Draw smoother Line

Since we know the lines are perfectly vertical, we can generate fixed number of points above and below the given point and draw them all. So, `drawBrustAtPoint()` changes to

    drawBrushAtPoint : function(pt, color, density) {
        this.renderTex.begin();
        for (var i = 0; i < density; i++) {
            this.chalkBrush = cc.Sprite.create(res.chalkBrush_png);
            this.chalkBrush.setRotation(Math.random() * 180);
            this.chalkBrush.setPosition(cc.p(pt.x, pt.y + 5 * (i - density * 0.5)));
            this.chalkBrush.setColor(color);
            this.chalkBrush.setScale(1.5);
            this.chalkBrush.visit();
        }
        this.renderTex.end();

        this.chalkSprite.setPosition(cc.p(pt.x - this.chalkSprite.getContentSize().width * 0.3,
            pt.y - this.chalkSprite.getContentSize().height * 0.2));
    }

We introduced a new parameter `density` and a `for` loop in the function.

  • Density determines how many points are drawn above and below to the given point. If density = 12, 6 points are drawn above and 6 points drawn below the given point.
  • For loop iterates `density` times, generating points with a gap of 5 pixels from each other.

Then in `updateDrawLine()`, change

this.drawBrushAtPoint(to, cc.color(250, 250, 50, 200));

to

this.drawBrushAtPoint(to, cc.color(250, 250, 50, 200), 16);

which means, we now draw 8 points above and below the given point `to`.

This should give us a smooth continuous line as this:

Line draw - Second

5. Draw vertical lines

We mastered drawing a single vertical line. Now let’s draw multiple vertical lines of the grid. Before starting to draw the lines, let’s create a `Config` object to make certain things simpler and configurable.

var Config = {};

Add this as the first line before the `Board` declaration. Then in the Board constructor, specify the properties of Config as follows:

Config.colCount         =   5;  // Number of columns in the grid
Config.rowCount         =   5;  // Number of rows in the grid
Config.drawSpeed        =   10; // Speed of Chalk Drawing
Config.lineColor        =   cc.color(250, 250, 50, 200); // Grid color

We dont want to draw in the full Board. But rather, let’s draw a square shapred box. To achieve that, add these 2 lines of code in the Board constructor:

this.boardSpace         =   cc.size(size.width * 0.75, size.width * 0.75);
this.cellSize           =   cc.size(this.boardSpace.width / Config.colCount, this.boardSpace.height / Config.rowCount);
  • boardSpace: This is pre-calculated area of the grid, which is now 75% of the width of the board.
  • cellSize: This is the size of each and every cell in the grid. It is calculated by dividing the boardSpace by row / column count.

Now we will replace the `updateDrawLine()` with a little more complex `updateVGridDraw()`. This will first draw a vertical line. Once it is over, it will increment x by some value and draw another vertical line. Keeps repeating this logic for `Config.colCount + 1` times. Here is the code for `updateVGridDraw()`

this.vLineIndex  = 0; // add this line in `drawBoard` function

updateVGridDraw              :   function(dt) {
    this.currentLinePercent         -=  0.01 * Config.drawSpeed;
    to                  =   cc.p(this.vLineIndex * this.cellSize.width, this.currentLinePercent * this.boardSpace.height);
    this.drawBrushAtPoint(to, Config.lineColor, 16);

    if (this.currentLinePercent < 0.01) {
        this.vLineIndex++;
        if (this.vLineIndex <= Config.colCount) {
            this.currentLinePercent = 1.0;
        } else {
            this.unschedule(this.updateVGridDraw);
        }
    }
}
  • vLineIndex: When drawing multiple lines, this variable keeps track of which line is being currently drawn. This also used to calculate the x position of the current line as in the following table.
    Table 1

    vLineIndex xPosition
    0 0
    1 cellSize.width
    2 cellSize.width * 2
    3 cellSize.width * 3
    n cellSize.width * n
  • Config.drawSpeed: This is a multiplier that determines by what percetange the `currentLinePercent` is getting changed. The more value it is, the point will be drawn at big distances and quickly.
  • Draw Point `to`: The draw point is then calculated with `vLineIndex` and `currentLinePercent`. For y position, rather than drawing to full board height, now we are only covering boardSpace.height, which is 75% of the width of the board.
  • We then call the `drawBrushAtPoint()` with calculated point `to`, which draws the dot with a given density of 16.
  • Other lines: The final `If` block is to draw further lines.
    • We check if the current line drawing is over, by checking if currentLinePercent reached 0.
    • When it is, we increment vLineIndex by 1 and reset currentLinePercent to 1. So a new line will get drawn but at the next x position.
    • When the vLineIndex reaches `Config.colCount`, we stop unschedule `updateVGridDraw()`, thus stopping the whole line drawing.

Vertical Lines Draw

6. Draw Grid

Now that we know how to draw Vertical lines, we can replicate the same and do it horizontally. Code update to draw horizontal lines.

updateHGridDraw              :   function(dt) {
    this.currentLinePercent         +=  0.01 * Config.drawSpeed;
    if (this.currentLinePercent > 0.93)
        this.currentLinePercent     =   0.931;
    to                  =   cc.p(this.currentLinePercent * this.boardSpace.width, this.hLineIndex * this.cellSize.height);
    this.drawBrushAtPoint(to, Config.lineColor, 16, false);

    if (this.currentLinePercent > 0.93) {
        this.hLineIndex--;
        if (this.hLineIndex != -1) {
            this.currentLinePercent =   -0.01;
        } else {
            this.unschedule(this.updateHGridDraw);
        }
    }
}

// update else block of `updateVGridDraw` with this code:
this.vLineIndex         =   -1;
this.hLineIndex         =   Config.rowCount;
this.currentLinePercent =   -0.01;
this.unschedule(this.updateVGridDraw);
this.schedule(this.updateHGridDraw, 0);

// update `drawBrushAtPoint` with this code:
drawBrushAtPoint            :   function(pt, color, density, vertical) { //new parameter vertical

// replace the line `this.chalkBrush.setPosition(...)` with this block inside `drawBrushAtPoint` function
if (vertical) {
    this.chalkBrush.setPosition(cc.p(pt.x, pt.y + 5 * (i - density * 0.5)));
} else {
    this.chalkBrush.setPosition(cc.p(pt.x + 5 * (i - density * 0.5), pt.y));
} 
  • `updateVGridDraw()` is very similar to `updateHGridDraw()`, except the x position is calculated by varying currentLinePercent and y position calculated by hLineIndex.
  • `drawBrushAtPoint()` gets a new boolean parameter vertical.
    • When vertical is true, adjacent filling dots are calculated vertically as in updateVGridDraw().
    • When vertical is false, adjacent filling dots are calculated horizontally as in updateHGridDraw().
  • Then the else block of updateVGridDraw() is replaced with above 5 lines of code, which unschedules the vertical line draw function, updateVGridDraw() and schedules the horizontal line draw function, updateHGridDraw().

At this point, we should be getting the output as follows:

Grid Lines Draw

7. Center in Board

The grid is now neatly drawn. But wait, it’s drawn over the edge wood portion. We need to bring it to the center of the board to make it look perfect. Considering what we done till now, centering the grid is just a piece of cake. Here is the logic:

Since the board size is 75% of the width, moving the board to 12.5% of the width will center the grid. So our layout would be like this.

|    space   |        board         |    space    |
      12%              75%                12%

To do this, create a new variable `offset` in the constructor as follows:

this.offset = cc.p(size.width * 0.12, size.height * 0.12);

Then update the point (to) calculation line in updateVGridDraw() and updateHGridDraw() as follows:

// updateVGridDraw()
to = cc.p(this.vLineIndex * this.cellSize.width + this.offset.x, this.currentLinePercent * this.boardSpace.height + this.offset.y);

// updateHGridDraw()
to = cc.p(this.currentLinePercent * this.boardSpace.width + this.offset.x, this.hLineIndex * this.cellSize.height + this.offset.y);

This will move our awesome Grid to the center.

Now you can tinker with the properties of Config object to draw grid of various sizes (7×7, 9×9), different chalk color and varying draw speed.

Center Grid Draw

Happy Chalking (y)

8. Complete Board.js Code

var Config                      =   {};

var Board = cc.Scene.extend({

    boardSprite                 :   null,

    renderTex                   :   null,

    chalkSprite                 :   null,

    chalkBrush                  :   null,

    prevPoint                   :   cc.p(0, 0),

    boardSpace                  :   null,

    cellSize                    :   null,

    offset                      :   null,

    mode                        :   0,

    ctor                        :   function () {

        this._super();

        var slf                 =   this;
        var size                =   cc.winSize;
        
        if( 'touches' in cc.sys.capabilities ) { 
            console.log('Can Touch');
            this._touchListener = cc.EventListener.create({
                event: cc.EventListener.TOUCH_ALL_AT_ONCE,
                onTouchesBegan: this.onTouchesBegan,
                onTouchesMoved: this.onTouchesMoved,
                onTouchesEnded: this.onTouchesEnded
            });

            cc.eventManager.addListener(this._touchListener, this);
        } else {
            console.log('No Touch Capabs');
        }

        Config.colCount         =   5;
        Config.rowCount         =   5;
        Config.drawSpeed        =   10;
        Config.lineColor        =   cc.color(250, 250, 50, 200);

        this.boardSpace         =   cc.size(size.width * 0.75, size.width * 0.75);
        this.cellSize           =   cc.size(this.boardSpace.width / Config.colCount, this.boardSpace.height / Config.rowCount);
        this.offset             =   cc.p(size.width * 0.12, size.height * 0.12);

        this.boardSprite        =   cc.Sprite.create(res.Board_BG);
        this.boardSprite.setPosition(cc.p(size.width / 2, size.height / 2));
        this.boardSprite.setScale(640 / this.boardSprite.getContentSize().width,
                size.height / this.boardSprite.getContentSize().height);
        this.addChild(this.boardSprite);

        this.renderTex     =   cc.RenderTexture.create(size.width, size.height);
        this.renderTex.setPosition(cc.p(size.width / 2, size.height / 2));
        this.addChild(this.renderTex);

        this.chalkSprite        =   cc.Sprite.create(res.chalk_png);
        this.chalkSprite.setPosition(cc.p(size.width * 0.7, this.chalkSprite.getContentSize().height * 0.8));
        this.addChild(this.chalkSprite, 2);

        this.duster             =   cc.Sprite.create(res.duster_png);
        this.duster.setPosition(cc.p(this.duster.getContentSize().width * 0.5, this.duster.getContentSize().height * 0.8));
        this.duster.setScale(0.5);
        this.duster.setRotation(30);
        this.addChild(this.duster, 2);

        this.drawBoard();
    }, 

    onTouchesBegan:function(touches, event) {
        var slf                 =   event.getCurrentTarget();
        var pos                 =   touches[0].getLocation();
        console.log('Began : ' + JSON.stringify(pos));
        
        slf.prevPoint           =   pos;
        slf.mode                =   0;

        dist                    =   Math.round(cc.pDistance(pos, slf.duster.getPosition()));
        if (dist < slf.duster.getContentSize().width) {
            slf.mode            =   1;
        }

        return                      true;
    },

    onTouchesMoved:function(touches, event) {
        var slf                 =   event.getCurrentTarget();
        var pos                 =   touches[0].getLocation();
        console.log('Move : ' + JSON.stringify(pos));
        //console.log('PrevPoint : ' + JSON.stringify(slf.prevPoint));

        var dist                =   Math.round(cc.pDistance(pos, slf.prevPoint));
        //console.log(dist);

        for (var i = 0; i < dist; i += 5) {
            var cPos            =   cc.pLerp(slf.prevPoint, pos, i/dist);
            if (slf.mode == 0) {
                slf.drawBrushAtPoint(cPos, cc.color(240, 240, 240, 230), 1, true);
            } else if (slf.mode == 1) {
                slf.eraseAtPoint(cPos);
            }
        }

        slf.prevPoint           =   pos;
    },

    onTouchesEnded              :   function(touches, event) {
        var slf                 =   event.getCurrentTarget();
        var pos                 =   touches[0].getLocation();
        var size                =   cc.winSize;

        console.log('End : ' + JSON.stringify(pos));

        if (slf.mode == 0) {
            slf.chalkSprite.runAction(cc.moveTo(0.2, cc.p(size.width * 0.7, slf.chalkSprite.getContentSize().height * 0.8)).easing(cc.easeIn(1.0)));
        } else if (slf.mode == 1) {
            slf.duster.runAction(cc.moveTo(0.2, cc.p(slf.duster.getContentSize().width * 0.5, slf.duster.getContentSize().height * 0.8)).easing(cc.easeIn(1.0)));
        }

    },

    drawBrushAtPoint            :   function(pt, color, density, vertical) {

        this.renderTex.begin();
        for (var i = 0; i < density; i++) {
            this.chalkBrush     =   cc.Sprite.create(res.chalkBrush_png);
            this.chalkBrush.setRotation(Math.random() * 180);
            if (vertical) {
                this.chalkBrush.setPosition(cc.p(pt.x, pt.y + 5 * (i - density * 0.5)));
            } else {
                this.chalkBrush.setPosition(cc.p(pt.x + 5 * (i - density * 0.5), pt.y));
            }
            this.chalkBrush.setColor(color);
            this.chalkBrush.setScale(1.5);
            this.chalkBrush.visit();
        }
        this.renderTex.end();

        this.chalkSprite.setPosition(cc.p(pt.x - this.chalkSprite.getContentSize().width * 0.3,
            pt.y - this.chalkSprite.getContentSize().height * 0.2));

    },

    eraseAtPoint                :   function(pt) {

        this.renderTex.begin();
        this.chalkBrush         =   cc.Sprite.create(res.chalkBrush_png);
        this.chalkBrush.setRotation(Math.random() * 180);
        this.chalkBrush.setPosition(pt);
        this.chalkBrush.setScale(10.0);
        this.chalkBrush.setOpacity(230);
        this.chalkBrush.setBlendFunc(  cc.ZERO, cc.ONE_MINUS_SRC_ALPHA );
        this.chalkBrush.visit();
        this.renderTex.end();

        this.duster.setPosition(pt);

    },

    drawBoard                   :   function(dt) {

        this.vLineIndex         =   0;
        this.hLineIndex         =   -1;
        this.currentLinePercent =   1.025;

        this.schedule(this.updateVGridDraw, 0);
    },

    updateVGridDraw              :   function(dt) {

        this.currentLinePercent         -=  0.01 * Config.drawSpeed;
        if (this.currentLinePercent < 0.08) 
            this.currentLinePercent = 0.079;
        to                  =   cc.p(this.vLineIndex * this.cellSize.width + this.offset.x, this.currentLinePercent * this.boardSpace.height + this.offset.y);
        this.drawBrushAtPoint(to, Config.lineColor, 16, true);

        if (this.currentLinePercent < 0.08) {
            this.vLineIndex++;
            if (this.vLineIndex <= Config.colCount) { this.currentLinePercent = 1.025; } else { this.vLineIndex = -1; this.hLineIndex = Config.rowCount; this.currentLinePercent = -0.01; this.unschedule(this.updateVGridDraw); this.schedule(this.updateHGridDraw, 0); } } }, updateHGridDraw : function(dt) { this.currentLinePercent += 0.01 * Config.drawSpeed; if (this.currentLinePercent > 0.93)
            this.currentLinePercent     =   0.931;
        to                  =   cc.p(this.currentLinePercent * this.boardSpace.width + this.offset.x, this.hLineIndex * this.cellSize.height + this.offset.y);
        this.drawBrushAtPoint(to, Config.lineColor, 16, false);

        if (this.currentLinePercent > 0.93) {
            this.hLineIndex--;
            if (this.hLineIndex != -1) {
                this.currentLinePercent =   -0.01;
            } else {
                this.unschedule(this.updateHGridDraw);
            }
        }
    }


});

Cocos2d-JS Tutorial – Chalk Board 2 – Erasing

Objective

In Continuation of our last Chalk Board drawing post, let’s see how to erase the board in this post.

ENGINE VERSION : COCOS2D-JS 3.8.1

Preview

Contents

  1. Prerequisite
  2. Download
  3. Chalk back to Position
  4. Draw / Erase Mode
  5. Touch Eraser Detection
  6. Erasing Magic
  7. Complete Board.js Code

At any point of time, refer to the source files Board.jsmain.js and resource.js for clarity.

1. Prerequisite

  • Should have Cocos2d-x installed in system.
  • Should have basic working knowledge of Cocos2d-JS
  • Read Previous post on Chalk Board Drawing.

See this link to get started with Cocos2d-x.

2. Download Code

Download project @ https://github.com/GethuGames/cocos2dx-chalk-board-draw/archive/erase1.0.zip Complete Project can be found in GITHUB.

Note: This is not directly executable. This contains the source and resources excluding the cocos2dx bundle. So, create a new project, download this github and replace the files in ur new project with this github files to be able to run the project.

3. Chalk back to Position

When you are erasing, you dont want the chalk to be in the middle of the board and overlap with the Eraser. So let’s create a action that will move the chalk to the bottom of the move after drawing (on touches ended).

// inside `onTouchesEnded` of Board.js
slf.chalkSprite.runAction(cc.moveTo(0.2, cc.p(size.width * 0.7, slf.chalkSprite.getContentSize().height * 0.8)).easing(cc.easeIn(1.0)));

Add that code in `onTouchesEnded`, so as to drop the chalk to bottom after each draw.

4. Draw / Erase Mode

As you have seen in the video above, we should be able to drag the Eraser to clear the board. So to separate erasing and drawing in the common action of dragging, lets define a variable `mode`.

     mode : 0,
  1. When mode is 0, our Canvas will be in drawing mode and
  2. When it is 1, it will be in Erasing mode.
  3. When the touch begins on Eraser, we set the mode to 1 and drag the eraser instead of chalk.
  4. Touching anywhere else other than Eraser, will set the mode to 0 and start drawing.

5. Touch Eraser Detection

Now in `touchesBegan`, we need to identify If the touch is made on Eraser and set the mode accordingly.

// This code goes in `onTouchesBegan` function of Board.js
        slf.mode                =   0;

        dist                    =   Math.round(cc.pDistance(pos, slf.duster.getPosition()));
        if (dist < slf.duster.getContentSize().width) {
            slf.mode            =   1;
        }

Above is a very simple Hit Test Logic.

  • Set the mode to 0 (Draw) by default.
  • Then find the distance between touch point (pos) and eraser.
  • If the distance is less than the size of the eraser itself, then set the mode to `1`, since the touch is made on or very close to the Eraser.

Also introduce a `if` condition inside the `for` loop of `onTouchesMoved`:

        for (var i = 0; i < dist; i += 5) {
            var cPos            =   cc.pLerp(slf.prevPoint, pos, i/dist);
            if (slf.mode == 0) {
                slf.drawBrushAtPoint(cPos, cc.color(240, 240, 240, 230));
            } else if (slf.mode == 1) {
                // Erase Code to be updated
            }
        }

Now, drawing lines will be called only when the mode is `0`. Try running the code and see what happens when you touch on Eraser and drag across the board. You will see no lines.

All pieces are now set. Let’s see how to do the actual erasing Magic.

6. Erasing Magic

Now close the function `drawBrushAtPoint()` to `eraseAtPoint`. All code will be similar to drawing, except for just one line, which is,

    this.chalkBrush.setBlendFunc( cc.ZERO, cc.ONE_MINUS_SRC_ALPHA );

Setting the blend function of the sprite to ( cc.ZERO, cc.ONE_MINUS_SRC_ALPHA ) will erase rather than drawing. That’s it. Very very simple. Here is the full code of `eraseAtPoint`.

    eraseAtPoint                :   function(pt) {
        this.renderTex.begin();
        this.chalkBrush         =   cc.Sprite.create(res.chalkBrush_png);
        this.chalkBrush.setRotation(Math.random() * 180);
        this.chalkBrush.setPosition(pt);
        this.chalkBrush.setScale(10.0);
        this.chalkBrush.setOpacity(230);
        this.chalkBrush.setBlendFunc(  cc.ZERO, cc.ONE_MINUS_SRC_ALPHA );
        this.chalkBrush.visit();
        this.renderTex.end();

        this.duster.setPosition(pt);
    }

See this is much similar to Drawing code, except for setting the Blend function. With different blend functions, some super awesome visuals can be created.

Erase Line

Happy Coding (y)

Complete Board.js Code

var Board = cc.Scene.extend({

    boardSprite                 :   null,

    renderTex                   :   null,

    chalkSprite                 :   null,

    chalkBrush                  :   null,

    prevPoint                   :   cc.p(0, 0),

    mode                        :   0,

    ctor                        :   function () {

        this._super();

        var slf                 =   this;
        var size                =   cc.winSize;
        
        if( 'touches' in cc.sys.capabilities ) { 
            console.log('Can Touch');
            this._touchListener = cc.EventListener.create({
                event: cc.EventListener.TOUCH_ALL_AT_ONCE,
                onTouchesBegan: this.onTouchesBegan,
                onTouchesMoved: this.onTouchesMoved,
                onTouchesEnded: this.onTouchesEnded
            });

            cc.eventManager.addListener(this._touchListener, this);
        } else {
            console.log('No Touch Capabs');
        }

        this.boardSprite        =   cc.Sprite.create(res.Board_BG);
        this.boardSprite.setPosition(cc.p(size.width / 2, size.height / 2));
        this.boardSprite.setScale(640 / this.boardSprite.getContentSize().width,
                size.height / this.boardSprite.getContentSize().height);
        this.addChild(this.boardSprite);

        this.renderTex     =   cc.RenderTexture.create(size.width, size.height);
        this.renderTex.setPosition(cc.p(size.width / 2, size.height / 2));
        this.addChild(this.renderTex);

        this.chalkSprite        =   cc.Sprite.create(res.chalk_png);
        this.chalkSprite.setPosition(cc.p(size.width * 0.7, this.chalkSprite.getContentSize().height * 0.8));
        this.addChild(this.chalkSprite, 2);

        this.duster             =   cc.Sprite.create(res.duster_png);
        this.duster.setPosition(cc.p(this.duster.getContentSize().width * 0.5, this.duster.getContentSize().height * 0.8));
        this.duster.setScale(0.5);
        this.duster.setRotation(30);
        this.addChild(this.duster, 2);
    }, 

    onTouchesBegan:function(touches, event) {
        var slf                 =   event.getCurrentTarget();
        var pos                 =   touches[0].getLocation();
        console.log('Began : ' + JSON.stringify(pos));
        
        slf.prevPoint           =   pos;
        slf.mode                =   0;

        /*
        var dist                =   Math.round(cc.pDistance(pos, slf.chalkSprite.getPosition()));
        if (dist < slf.chalkSprite.getContentSize().width) {
            slf.mode            =   0;
        }
        */

        dist                    =   Math.round(cc.pDistance(pos, slf.duster.getPosition()));
        if (dist < slf.duster.getContentSize().width) {
            slf.mode            =   1;
        }

        return                      true;
    },

    onTouchesMoved:function(touches, event) {
        var slf                 =   event.getCurrentTarget();
        var pos                 =   touches[0].getLocation();
        console.log('Move : ' + JSON.stringify(pos));
        //console.log('PrevPoint : ' + JSON.stringify(slf.prevPoint));

        var dist                =   Math.round(cc.pDistance(pos, slf.prevPoint));
        //console.log(dist);

        for (var i = 0; i < dist; i += 5) {
            var cPos            =   cc.pLerp(slf.prevPoint, pos, i/dist);
            if (slf.mode == 0) {
                slf.drawBrushAtPoint(cPos, cc.color(240, 240, 240, 230));
            } else if (slf.mode == 1) {
                slf.eraseAtPoint(cPos);
            }
        }

        slf.prevPoint           =   pos;
    },

    onTouchesEnded              :   function(touches, event) {
        var slf                 =   event.getCurrentTarget();
        var pos                 =   touches[0].getLocation();
        var size                =   cc.winSize;

        console.log('End : ' + JSON.stringify(pos));

        if (slf.mode == 0) {
            slf.chalkSprite.runAction(cc.moveTo(0.2, cc.p(size.width * 0.7, slf.chalkSprite.getContentSize().height * 0.8)).easing(cc.easeIn(1.0)));
        } else if (slf.mode == 1) {
            slf.duster.runAction(cc.moveTo(0.2, cc.p(slf.duster.getContentSize().width * 0.5, slf.duster.getContentSize().height * 0.8)).easing(cc.easeIn(1.0)));
        }
                //this.duster.runAction(cc.moveTo(0.1, this.erasePoint).easing(cc.easeIn(1.0)));

    },

    drawBrushAtPoint            :   function(pt, color) {

        this.renderTex.begin();
        this.chalkBrush         =   cc.Sprite.create(res.chalkBrush_png);
        this.chalkBrush.setRotation(Math.random() * 180);
        this.chalkBrush.setPosition(pt);
        this.chalkBrush.setColor(color);
        this.chalkBrush.setScale(1.5);
        this.chalkBrush.visit();
        this.renderTex.end();

        this.chalkSprite.setPosition(cc.p(pt.x - this.chalkSprite.getContentSize().width * 0.3,
            pt.y - this.chalkSprite.getContentSize().height * 0.2));

    },

    eraseAtPoint                :   function(pt) {

        this.renderTex.begin();
        this.chalkBrush         =   cc.Sprite.create(res.chalkBrush_png);
        this.chalkBrush.setRotation(Math.random() * 180);
        this.chalkBrush.setPosition(pt);
        this.chalkBrush.setScale(10.0);
        this.chalkBrush.setOpacity(230);
        this.chalkBrush.setBlendFunc(  cc.ZERO, cc.ONE_MINUS_SRC_ALPHA );
        this.chalkBrush.visit();
        this.renderTex.end();

        this.duster.setPosition(pt);

    }

});

Cocos2d-JS Tutorial – Chalk Board 1 – Drawing and Animations

A Comeback post after around 2 years :-)

Objective

In this post, we will see how to create a Cool Chalk board drawing functionality in Cocos2d-JS with RenderTexture. Later we will also see how to erase the Board with the Eraser.

Engine Version : Cocos2d-JS 3.8.1

Preview

Contents

  1. Prerequisite
  2. Resources
  3. Download Code
  4. Setup the Chalk Board
  5. Setup Touch functions
  6. Basic Drawing (Dotted)
  7. Smooth Drawing
  8. Complete Board.js Code

At any point of time, refer to the source files Board.jsmain.js and resource.js for clarity

1. Prerequisite

  • Should have Cocos2d-x installed in system.
  • Should have basic working knowledge of Cocos2d-JS

See this link to get started with Cocos2d-x.

2. Resources

Download and Copy these to the `res/` folder.

3. Download Code

Download project @ https://github.com/GethuGames/cocos2dx-chalk-board-draw/archive/draw1.0.zip Complete Project can be found in GITHUB.

Note: This is not directly executable. This contains the source and resources excluding the cocos2dx bundle. So, create a new project, download this github and replace the files in ur new project with this github files to be able to run the project.

4. Setup the Chalk Board

  • Create a Scene `Board`
  • In the constructor of `Board` scene, add the sprites for Chalk Board, Chalk Piece and Eraser as follows:
// This code goes in `ctor` function of Board.js
var size = cc.winSize;

this.boardSprite = cc.Sprite.create(res.Board_BG);
this.boardSprite.setPosition(cc.p(size.width / 2, size.height / 2));
this.boardSprite.setScale(640 / this.boardSprite.getContentSize().width,
size.height / this.boardSprite.getContentSize().height);
this.addChild(this.boardSprite);

this.chalkSprite = cc.Sprite.create(res.chalk_png);
this.chalkSprite.setPosition(cc.p(100, 200));
this.addChild(this.chalkSprite, 2);

this.duster = cc.Sprite.create(res.duster_png);
this.duster.setPosition(cc.p(this.duster.getContentSize().width * 0.5, this.duster.getContentSize().height * 0.8));
this.duster.setScale(0.5);
this.duster.setRotation(30);
this.addChild(this.duster, 2);
  • Then add the `RenderTexture` which will act the real chalk board to draw with the following code.
// This code goes in `ctor` function of Board.js
this.renderTex     =   cc.RenderTexture.create(size.width, size.height);
this.renderTex.setPosition(cc.p(size.width / 2, size.height / 2));
this.addChild(this.renderTex);

Then update the `main.js` to run the `Board` scene:

// This code goes in `onStart` function of main.js
cc.view.setDesignResolutionSize(640, 960, cc.ResolutionPolicy.FIXED_WIDTH);

cc.director.runScene(new Board());

This should display the Chalk Board.

Board Setup

5. Setup Touch Functions

Again in the constructor create Event Listeners to capture touch Began, Move and End.

// This code goes in `ctor` function of Board.js
if( 'touches' in cc.sys.capabilities ) { 
    console.log('Can Touch');
    this._touchListener = cc.EventListener.create({
        event: cc.EventListener.TOUCH_ALL_AT_ONCE,
        onTouchesBegan: this.onTouchesBegan,
        onTouchesMoved: this.onTouchesMoved,
        onTouchesEnded: this.onTouchesEnded
    });
    cc.eventManager.addListener(this._touchListener, this);
} else {
    console.log('No Touch Capabs');
}

Now add touch handlers to the `Board` scene

onTouchesBegan:function(touches, event) {
    var pos                 =   touches[0].getLocation();
    console.log('Began : ' + JSON.stringify(pos));

    return                      true;
},

onTouchesMoved:function(touches, event) {
    var pos                 =   touches[0].getLocation();
    console.log('Move : ' + JSON.stringify(pos));
},

onTouchesEnded              :   function(touches, event) {
    var pos                 =   touches[0].getLocation();
    console.log('End : ' + JSON.stringify(pos));
}

If this is set right, the app should throw logs in the console on touch and drag.

Chalk Board with Console log

6. Basic Drawing (Dotted)

Let’s create a new function that will handle the actual drawing.

drawBrushAtPoint            :   function(pt, color) {
    this.renderTex.begin(); //a
    this.chalkBrush         =   cc.Sprite.create(res.chalkBrush_png); //b
    this.chalkBrush.setRotation(Math.random() * 180); //c
    this.chalkBrush.setPosition(pt); //d
    this.chalkBrush.setColor(color); //e
    this.chalkBrush.visit(); //f
    this.renderTex.end(); //g

    this.chalkSprite.setPosition(cc.p(pt.x - this.chalkSprite.getContentSize().width * 0.3,
        pt.y - this.chalkSprite.getContentSize().height * 0.2)); //h

}

This is where the magic happens. Let’s go through this code line by line.
a : Prepares the Render Texture for Drawing.
b : Creates the brush texture sprite.
c, d, e : Set’s the rotation (random), position (as given) and color(as given) of the texture.
f : Draws the brush texture in the render texture.
g : Closes the Render Texture
h : Set’s the Chalk Sprite’s position to given position

We will call this function from touchesMoved passing the current touch Position and the color of the chalk.

onTouchesMoved:function(touches, event) {
    var slf                 =   event.getCurrentTarget();
    var pos                 =   touches[0].getLocation();
    slf.drawBrushAtPoint(cPos, cc.color(240, 240, 240, 230));
},

Now, you should be able to draw in the canvas by dragging over it.

Preview:

Dotted Draw

But the chalk line is not continuous and when drag faster, it dots the board rather than drawing lines. It’s because the touchesMoved is invoked between distant points when you move faster. Like when you drag really faster, you are at (50, 50) in one cycle and in (100, 150) in the next. Thus drawing 2 dots, one at (50, 50) and other at (100, 150).

No worries, we can fix this with some techniques.

7. Smooth Drawing

To get the drawing smoother, we will interpolate points between two distant `touch move` points and draw there. To do this, update `touchesMoved` function with the following:

onTouchesMoved:function(touches, event) {
    var slf                 =   event.getCurrentTarget();
    var pos                 =   touches[0].getLocation();
    console.log('Move : ' + JSON.stringify(pos));

    var dist                =   Math.round(cc.pDistance(pos, slf.prevPoint)); //A

    for (var i = 0; i < dist; i += 5) { //B
        var cPos            =   cc.pLerp(slf.prevPoint, pos, i/dist);
        slf.drawBrushAtPoint(cPos, cc.color(240, 240, 240, 230));
    }

    slf.prevPoint           =   pos;
},
  • At the end of each `touchesMove` function, we store the point as `prevPoint`.
  • Then on next call of `touchesMove`, we get the distance between current Move position and previous move position (Line A)
  • We create a for loop that will advance 5 pixels from Zero to the distance between 2 points.
  • Inside the loop, we interpolate the corresponding point between the previous point and current points and draw the chalk brush there.
  • This way we will fill the gap between the dots and get a smooth Drawing..

Smooth Draw

Hope this Tutorial is useful :-)

Next Tuturial will be on erasing the board. Subscribe to get Notified.

Happy Coding (y)

Complete Board.js Code

var Board = cc.Scene.extend({

    boardSprite                 :   null,

    renderTex                   :   null,

    chalkSprite                 :   null,

    chalkBrush                  :   null,

    prevPoint                   :   cc.p(0, 0),

    ctor                        :   function () {

        this._super();

        var slf                 =   this;
        var size                =   cc.winSize;
        
        if( 'touches' in cc.sys.capabilities ) { 
            console.log('Can Touch');
            this._touchListener = cc.EventListener.create({
                event: cc.EventListener.TOUCH_ALL_AT_ONCE,
                onTouchesBegan: this.onTouchesBegan,
                onTouchesMoved: this.onTouchesMoved,
                onTouchesEnded: this.onTouchesEnded
            });

            cc.eventManager.addListener(this._touchListener, this);
        } else {
            console.log('No Touch Capabs');
        }

        this.boardSprite        =   cc.Sprite.create(res.Board_BG);
        this.boardSprite.setPosition(cc.p(size.width / 2, size.height / 2));
        this.boardSprite.setScale(640 / this.boardSprite.getContentSize().width,
                size.height / this.boardSprite.getContentSize().height);
        this.addChild(this.boardSprite);

        this.renderTex     =   cc.RenderTexture.create(size.width, size.height);
        this.renderTex.setPosition(cc.p(size.width / 2, size.height / 2));
        this.addChild(this.renderTex);

        this.chalkSprite        =   cc.Sprite.create(res.chalk_png);
        this.chalkSprite.setPosition(cc.p(100, 200));
        this.addChild(this.chalkSprite, 2);

        this.duster             =   cc.Sprite.create(res.duster_png);
        this.duster.setPosition(cc.p(this.duster.getContentSize().width * 0.5, this.duster.getContentSize().height * 0.8));
        this.duster.setScale(0.5);
        this.duster.setRotation(30);
        this.addChild(this.duster, 2);
    }, 

    onTouchesBegan:function(touches, event) {
        var slf                 =   event.getCurrentTarget();
        var pos                 =   touches[0].getLocation();
        
        slf.prevPoint           =   pos;

        return                      true;
    },

    onTouchesMoved:function(touches, event) {
        var slf                 =   event.getCurrentTarget();
        var pos                 =   touches[0].getLocation();
        //console.log('Move : ' + JSON.stringify(pos));
        //console.log('PrevPoint : ' + JSON.stringify(slf.prevPoint));

        var dist                =   Math.round(cc.pDistance(pos, slf.prevPoint));
        //console.log(dist);

        for (var i = 0; i < dist; i += 5) {
            var cPos            =   cc.pLerp(slf.prevPoint, pos, i/dist);
            slf.drawBrushAtPoint(cPos, cc.color(240, 240, 240, 230));
        }

        slf.prevPoint           =   pos;
    },

    onTouchesEnded              :   function(touches, event) {
        var pos                 =   touches[0].getLocation();
        console.log('End : ' + JSON.stringify(pos));

    },

drawBrushAtPoint            :   function(pt, color) {

    this.renderTex.begin();
    this.chalkBrush         =   cc.Sprite.create(res.chalkBrush_png);
    this.chalkBrush.setRotation(Math.random() * 180);
    this.chalkBrush.setPosition(pt);
    this.chalkBrush.setColor(color);
    this.chalkBrush.setScale(1.5);
    this.chalkBrush.visit();
    this.renderTex.end();

    this.chalkSprite.setPosition(cc.p(pt.x - this.chalkSprite.getContentSize().width * 0.3,
        pt.y - this.chalkSprite.getContentSize().height * 0.2));

}

});