Ellipse Class for KineticJS

I’ve been taking a look at the KineticJS library in recent weeks. I wanted to draw an ellipse, rather than a circle and did a little Googling before discovering a solution.

The solution, once I saw it, was a lot more obvious than I was expecting. I decided to extend the Kinetic.js Shape object with an Ellipse object as detailed in the following code block:

///////////////////////////////////////////////////////////////////////
//  Ellipse
///////////////////////////////////////////////////////////////////////
/**
 * Ellipse constructor
 * @constructor
 * @augments Kinetic.Shape
 * @param {Object} config
 */
Kinetic.Ellipse = function(config) {
    this.setDefaultAttrs({
        width: 0,
        height: 0
    });

    this.shapeType = "Ellipse";

    config.drawFunc = function() {
        var canvas = this.getCanvas();
        var context = this.getContext();

		var w = this.attrs.width / 2;
		var h = this.attrs.height / 2;
		var xPos, yPos;

		context.beginPath();
		this.applyLineJoin();

		for (var i = 0 * Math.PI; i < 2 * Math.PI; i += 0.1 ) { // was 0.01 but slow with lots of circles

		    xPos = (0 + (this.attrs.width / 2)) - (h * Math.sin(i)) * Math.sin(0 * Math.PI) + (w * Math.cos(i)) * Math.cos(0 * Math.PI);
		    yPos = (0 + (this.attrs.height / 2)) + (w * Math.cos(i)) * Math.sin(0 * Math.PI) + (h * Math.sin(i)) * Math.cos(0 * Math.PI);

		    if (i == 0) {
		        context.moveTo(xPos, yPos);
		    } else {
		        context.lineTo(xPos, yPos);
		    }
		}
		context.closePath();
		this.fillStroke();
    };
    // call super constructor
    Kinetic.Shape.apply(this, [config]);
};
/*
 * Ellipse methods
 */
Kinetic.Ellipse.prototype = {
    /**
     * set width
     * @param {Number} value
     */
    setWidth: function(value) {
        this.attrs.width = value;
    },
    /**
     * get width
     */
    getWidth: function() {
        return this.attrs.width;
    },
    /**
     * set height
     * @param {Number} value
     */
    setHeight: function(value) {
        this.attrs.height = value;
    },
    /**
     * get width
     */
    getHeight: function() {
        return this.attrs.height;
    }
};

// extend Shape
Kinetic.GlobalObject.extend(Kinetic.Ellipse, Kinetic.Shape);

One Response to Ellipse Class for KineticJS