KLAC logo KLAC Word puzzle Available for

How to draw a solid circle with Cocos2d-JS

Cocos2d-js doesn’t provide a single function to draw a solid circle. You have to use a combination of primitive calls to obtain one.

Here’s a little trick to draw a circle and fill it. It’s fast and very effective as it doesn’t add any draw calls. It just exploits some not-exposed internal members of the canvas rendering wrapper.

1
var node = new cc.DrawNode();
2
node.drawCircle(center, radius, ...other params);
3
//workaround to fill the circle
4
var lastElement = node._buffer[node._buffer.length - 1];
5
lastElement.isFill = true;
6
lastElement.fillColor = cc.color.WHITE; // the fill color

If you’re in the need to use this function often, thanks to javascript prototype feature, you can enrich the cc.DrawNodeCanvas.prototype with this operation.

1
/**
2
* @param {cc.point} center - x and y coord of the circle center
3
* @param {number} radius - circle radius length    
4
* @param {cc.color} color - circle fill color
5
* @param {cc.color} [borderColor] - Optional circle border color.
6
* @param {number} [borderWidth] - Optional circle border width.
7
* @param {number} [segments] - Optional circle segments, aka definition. (default 24).    
8
*/
9
cc.DrawNodeCanvas.prototype.drawSolidCircle = function (center, radius, color, borderColor, borderWidth, segments) {
10
    this.drawCircle(center, radius, 0, segments || 24, false, borderWidth || 0, borderColor || color);
11
    //set the fill mode and color
12
    var lastElement = this._buffer[this._buffer.length - 1];
13
    lastElement.isFill = true;
14
    lastElement.fillColor = color;     
15
}

Put the code right after the cocos-js script import and you can call drawSolidCircle function in your own game code as it was part of the framework.

1
var node = new cc.DrawNode();
2
node.drawSolidCircle(center, radius, color);

Hope this trick make your life easier.
Keep coding.

Discaimer
As stated this snippet works only in canvas mode. For WebGL you should use standard cocos-js API.

This website uses cookies to improve your experience