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
Solution 1:
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");
varTriangle=( function(){
var self;
functionTriangle(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 yetvarT1=newTriangle(0,0,'gold');
varT2=newTriangle(150,30,'red');
varT3=newTriangle(300,60,'green');
// draw the triangles onto the canvasT1.draw(ctx);
T2.draw(ctx);
T3.draw(ctx);
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvasid="canvas"width=512height=512></canvas>
Solution 2:
After @markE answer I updated my code this way, just to clean it up a bit. I also followed Kaiido comment in order to improve performances.
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
//------------------------------// TRIANGLE SETUPclassTriangle {
constructor( x = 0, y = 0, fillColor = '#000') {
// Settingsthis.x = x;
this.y = y;
this.fillColor = fillColor;
// Setup everything once parameters are setupthis.setup();
}
setup() {
// Move context to position
ctx.translate( this.x, this.y );
// Draw from new context positionthis.draw();
// Restore context back to initial position
ctx.setTransform(1,0,0,1,0,0);
}
draw() {
// Draw triangle
ctx.beginPath();
ctx.lineTo( 0, 0 );
ctx.lineTo( 80, 80 );
ctx.lineTo( 0, 160 );
ctx.closePath();
// Fill color
ctx.fillStyle = this.fillColor;
ctx.fill();
}
}
// Create Triangle instancesvarT1 = newTriangle( 160, 20 );
varT2 = newTriangle( 20, 80, 'red' );
#canvas { background-color: #EEE; }
<canvasid="canvas"width=512height=512></canvas>
Post a Comment for "How To Create Multiple Instances Of The Same Shape In Html Canvas?"