Extendiendo canvas-event

Si necesita crear varias veces la misma figura, extender canvas-event es la mejor opción.

Para agregar una figura nueva, debe extender un objetos predefinidos: Circle, Rect, Line, Path, Image, Arc o Shape y sobreescribir los métodos init y draw.

Nota: se debe llamar el método init del objeto padre (mediante _super) con los argumentos apropiados para heredar.

var Tetro = Cevent.Shape.extend({
    init: function(x, y, scale) {
        this.scale = scale;
        // llamar método padre con argumentos apropiados
        this._super(x, y);
    },

    draw: function(ctx){
        // para acortar las expresiones
        var s = this.scale;

        ctx.save(); // guardar estado actual del canvas
        this.applyStyle(ctx); // aplicar estilo
        this.setTransform(ctx); // aplicar transformaciones


        // dibujar tetrominó según escala
        Cevent.setContext(ctx)
        .M(this.x, this.y)
        .h(3 * s).v(-s).h(-s).v(-s).h(-s).v(s).h(-s).z();

        // rellenar y/o delinear figura
        this.fill_or_stroke(ctx);

        // restaurar estado anterior del canvas
        ctx.restore();
    },
});

// registrar el objeto nuevo
Cevent.register("car", Car);

// usar objeto nuevo
ce.car(30, 30, 10).drag().draw();

Related Topics

This Page

Fork me on GitHub