Rendering shapes in Canvas using objects

In a previous blog post (Painting using Canvas and JS), I explained how to paint a figure using canvas. I explained how to paint the figure inside a single function by setting coordinates and calling stroke and fill. In the following post, (Create an interactive HTML5 Canvas using event handlers.) I presented the clickable area as an object. In this, post I am going to start up by combining the two like the snippet below.



I create an object called CustFigure. It has X and Y values and a height and width. This is all we need in order to place it in the grid and to get the size of the figure, say a box.
 
 var CustFigure = function (x, y, height, width, label ) {
    this.x = x;
    this.y = y;
    this.height = height;
    this.width = width;
    this.label = label;
    };
 
function DrawShape(Shape){
    var rectWidth = Shape.width;
    var rectHeight = Shape.height;
    var rectX = Shape.x;
    var rectY = Shape.y;

    renderContext.beginPath();
    renderContext.fillRect(rectX, rectY, rectWidth, rectHeight);
}

// This call is sending the object to the function DrawShape(), rendering the shape.
DrawShape(CustFigure);
If you want to render many shapes, you can take the following approach. Create an array as a container for all your figures and push each instance of CustFigure in it.
var custFigures = [];

var custFigure1 = new CustFigure(10, 10, 75+10, 75+10, " Hello Nerd!");
custFigures.push(custFigure1);
var custFigure2 = new CustFigure(20, 20, 75+20, 75+20, " Hello Nerd!");
custFigures.push(custFigure2);
var custFigure3 = new CustFigure(30, 30, 75+30, 75+30, " Hello Nerd!");
custFigures.push(custFigure3);
Now, calling the function renderLoop, we render all the shapes in the array.
// Loops through the custom shape array calling DrawShape on every shape
function renderLoop() {
    var i = custFigures.length;
    while (i-- && i >= 0) {
        var customShape = custFigures[i];
        DrawShape(customShape, i, context);
    }
}

Comments

Popular posts from this blog

Power Pages Manifest Explained related to Collaborative Development and ALM

Exploring the Power of Variables in Liquid and Power Pages

Create an interactive HTML5 Canvas using event handlers.