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

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
2
var node = new cc.DrawNode();
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