Ir al contenido principal

Canvas - Dibujando poligonos con Javascript (Herencia y pseudo polimorfismo)

En el ejemplo anterior definimos de una manera muy basica varios poligonos, bueno decidi buscar la manera de pintarlos en un lienzo (canvas) y aqui el resultado (ojo necesitas un browser que soporte HTML 5)

Lo primero el HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Figure Example</title>
</head>
<body>

    <canvas id="myCanvas" width="300" height="300" style="border: solid 1px black"></canvas>


    <script type="text/javascript" src="figure.js"></script>

</body>
</html>

Note q al javascript le hemos dado el nombre de figure.js

Seguidamente el codigo con el canvas, es bastante sencillo para mas detalles busque la documentacion de cada metodo.



/**
 * User: jsanca
 * Date: 6/12/13
 * Time: 11:10 PM
 */

// Defines a point
function Point (x, y) {

    this.x = x;
    this.y = y;
} // Point


// Basic definition of a Figure, just a point in nowhere.
function Figure (point, name) {

    this.point = point;
    this.name = name;

    this.render = function (context) {

        console.log("figure: " + this.name + " " +this.point);
    }
} // Figure.

// the points defines some of the sides
function Square (point1, point2, name) {

    Figure.call(this, point1, name);
    this.point2 = point2;

    this.side = function () {

        var side =
            (this.point2.x == this.point.x)?
                this.point2.y - this.point.y:
                this.point2.x - this.point.x;

        return Math.abs(side);
    }

    this.area = function () {

        var side = this.side();

        return Math.pow(side, 2);
    }

    this.render = function (context) {

        // render out the square.
        var side = this.side();

        context.fillStyle = "rgb(0,0,255)";
        context.fillRect (this.point.x, this.point.y, side, side);

        console.log("square: " + this.name + ", area = " + this.area());
    }
} // Square.

Square.prototype.parent = Figure.prototype;
Square.prototype.constructor = Square;

// the points defines the point angles
function Triangle (point1, point2, point3, name) {

    Figure.call(this, point1, name);
    this.point2 = point2;
    this.point3 = point3;

    this.area = function () {

        var base = 0;
        var verticalHeight = 0;

        if (this.point2.x == this.point.x) {

            base = this.point2.y - this.point.y;
            verticalHeight = this.point.x - this.point3.x;
        } else {

            base = this.point2.x - this.point.x;
            verticalHeight = this.point.y - this.point3.y;
        }


        return 0.5 * Math.abs(base) * Math.abs(verticalHeight);
    }

    this.render = function (context) {

        console.log("triangle: " + this.name + ", area = " + this.area());

        // the triangle tooks a base point and them move to the rest of the angle point
        context.fillStyle = "rgb(255,0,0)";

        context.beginPath();
        context.moveTo(this.point.x,this.point.y);
        context.lineTo(this.point2.x,this.point2.y);
        context.lineTo(this.point3.x,this.point3.y);

        context.fill();
    }
} // Triangle.

Triangle.prototype.parent = Figure.prototype;
Triangle.prototype.constructor = Triangle;

// the points you pass are the diagonal of the rectangle.
function Rectangle (point1, point2, name) {

    Figure.call(this, point1, name);
    this.point2 = point2;

    this.width = function () {

        return Math.abs(this.point2.x - this.point.x);
    }

    this.height = function () {

        return Math.abs(this.point2.y - this.point.y);
    }


    this.area = function () {

        return this.width() * this.height();
    }

    this.render = function (context) {

        console.log("rectangle: " + this.name + ", area = " + this.area());

        context.fillStyle = "rgb(0,255, 0)";
        context.fillRect (this.point.x, this.point.y, this.width(), this.height());

    }
} // Rectangle.

Rectangle.prototype.parent = Figure.prototype;
Rectangle.prototype.constructor = Rectangle;

// the points defines the radius
function Circle (point1, point2, name) {

    Figure.call(this, point1, name);
    this.point2 = point2;

    this.radius = function () {

        var radius =
            (this.point2.x == this.point.x)?
                this.point2.y - this.point.y:
                this.point2.x - this.point.x;

        return Math.abs(radius);
    }

    this.circumference = function () {

        var radius = this.radius();

        return 2 * Math.PI * radius;
    }

    this.area = function () {

        var radius = this.radius();

        return Math.PI * Math.pow(radius, 2);
    }

    this.render = function (context) {

        var radius = this.radius();

        console.log("circle: " + this.name + ", area = " + this.area() + ", circumference = " + this.circumference() + ", radius = " + radius);

        context.fillStyle = "rgb(255,255, 0)";

        context.beginPath();
        context.arc(this.point.x, this.point.y, radius , 0,2 * Math.PI);
        context.stroke();
    }
} // Circle.

Circle.prototype.parent = Figure.prototype;
Circle.prototype.constructor = Circle;

console.log("Running");
var figuresArray = new Array(
    new Square  (new Point(10,10), new Point(10,30), "Cuadrado 1"),
    new Square  (new Point(10,50), new Point(20,50), "Cuadrado 2"),
    new Triangle(new Point(10,10), new Point(10,20), new Point(0,15), "Mi Triangulito"),
    new Triangle(new Point(100,100), new Point(60,160), new Point(160,160), "Triangulo grande"),
    new Rectangle(new Point(80,50), new Point(90,80), "Mi Rectangulo"),
    new Circle(new Point(200,200), new Point(200,225), "Mi Circulo")
);

var canvas = document.getElementById('myCanvas');
var context =  (canvas.getContext)?
    canvas.getContext('2d'):null;


    figuresArray.forEach(
    function(entry) {

        console.log(entry);
        entry.render(context);
    }
);


Ejecutalo para ver el resultado :) cada figura tiene un color diferente

Comentarios

aida ardani dijo…
https://timearamesh.com/the-difference-between-a-psychiatrist-and-a-psychologist/It can be said with certainty that one of the most important branches of medicine is psychiatry. This field has gained a lot of fans recently, and if you look at the universities and look at their statistics, you will see how much it has been accepted.

Entradas más populares de este blog

Pasos para remover Postgresql 8.3 en MAC OS

Tomado de: http://forums.enterprisedb.com/posts/list/1437.page In Mac OSX: (Assuming Default Locations) Via uninstaller: 1) In the installation directory, there will be a uninstall-postgresql.app file will be there, executing (double clicking) that will uninstall the postgresql installation. Manual Uninstallation: 1) Stop the server sudo /sbin/SystemStarter stop postgresql-8.3 2) Remove menu shortcuts: sudo rm -rf /Applications/PostgreSQL 8.3 3) Remove the ini file sudo rm -rf /etc/postgres-reg.ini 4) Removing Startup Items sudo rm -rf /Library/StartupItems/postgresql-8.3 5) Remove the data and installed files sudo rm -rf /Library/PostgreSQL/8.3 6) Delete the user postgres sudo dscl . delete /users/postgres

Enrique Bunbury - 3 de Octubre 2009 - Heredia CR

Via periodico la nacion, me entero de este conciertazo: http://www.nacion.com/viva/2009/julio/29/viva2042768.html Ah esperar mas detalles y la venta de la entradas, "Para solo si me perdonas ..." EDIT ..... Via http://www.enriquebunbury.com/hellville.aspx (gracias a andres por su post) venta anticipada: Entradas a la venta a partir del 13 de agosto en: www.costaricaticket.com Por ahi estare anunciando, el 13 si las estan vendiendo!

Configura tu MMS - ICE CELULAR

Hola gente, Me encontre esta para configurar en tu aparato el servicio del ICE, para enviar mensajes con Imagen: http://www.grupoice.com/esp/serv/per/cel/catal_sm/men_multi/guia.htm En mi caso yo tengo un K550i, aunque no vi mi modelo dentro de la lista que dan en el PDF, me guié con el modelo mas similar y funko. Como dato curioso si envía un mensaje a un celular sin soporte o conflagración MMS, el ICE manda un link y credenciales para ver el mensaje en: http://mms.grupoice.com/m/C?url=mmc1 upd (edit): Para que funcione los MMS debe tener instalado Internet en su Celular; el costo por tarifa fija, es de 3500 colones por mes. update (dic 29 2010) Me encontré estos otros links con mas info: http://portal.grupoice.com/wps/wcm/connect/web+content/Esp/CatTelecom/movil/Adicionales/Kolbiemail/como/ http://www.taringa.net/posts/celulares/7987334/Kolbi-Prepago-todas-la-configuraciones.html También puedes ver mas, en el thread del facebook de Kolbi http://www.facebook.com/photo.php?fbid=1720708...