a.barbieri a.barbieri - 3 months ago 8
Javascript Question

How to create multiple instances of the same shape in HTML canvas?

I'm trying to create a canvas with several triangles all over the place.

I would like to create a class of a path in order to instantiate it multiple times. I've tried that:

class Triangle {

constructor( x = 0, y = 0 ) {

// Get context from the global variable 'ctx'
this.ctx = ctx;

// Draw triangle
this.ctx.beginPath();
this.ctx.lineTo( 0 , 0 );
this.ctx.lineTo( 80 , 80 );
this.ctx.lineTo( 0 , 160 );
this.ctx.moveTo( x , y );
this.ctx.closePath();

// Place color
this.ctx.fillStyle = '#000';
this.ctx.fill();
}
}


Unfortunately if I do that it works just with the first element. Meaning that the result is two triangles on 0,0 position...

var T1 = new Triangle( 0, 0 );
var T2 = new Triangle( 10, 10 );


How can I create multiple triangles and reference to them singularely?




EDIT



After @markE answer I updated my code here below.

Answer

You can use context.translate to offset your [0,0] triangles to any new coordinate on the canvas.

When you translate you're actually moving the [0,0] canvas origin to a specified [x,y]. This causes anything drawn after translate to be drawn with an [x,y] offset.

An added benefit of translate is that you don't need to modify the coordinates of your triangle -- translate automatically does that for you!

Example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

var Triangle=( function(){
    var self;
    function Triangle(x,y,fillcolor){
        self=this;
        this.x=x;
        this.y=y;
        this.fillcolor=fillcolor;
    }
    Triangle.prototype.draw=function(ctx){
        // offset the [0,0] triangle to [x,y]
        ctx.translate(this.x,this.y);
        // Define triangle
        ctx.beginPath();
        ctx.lineTo( 0  , 0   );
        ctx.lineTo( 80 , 80  );
        ctx.lineTo( 0  , 160 );
        ctx.closePath();
        // fill triangle
        ctx.fillStyle = this.fillcolor;
        ctx.fill();
        // always clean up! Undo the translation    
        ctx.translate(-this.x,-this.y);
    };
    return(Triangle);
})();

// create new triangles, but don't draw them yet
var T1=new Triangle(0,0,'gold');
var T2=new Triangle(150,30,'red');
var T3=new Triangle(300,60,'green');

// draw the triangles onto the canvas
T1.draw(ctx);
T2.draw(ctx);
T3.draw(ctx);
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=512 height=512></canvas>

Comments