HTML5 Canvas - Draw Shape2

by black strings

HTML

<div id="testContainer">
  <p>
  The css controls the border and sizing of the image and margin.
  The left,top,right,bottom inside paddings, are actual paddings when drawing the shape. 
  </p>
</div>

CSS

img { 
  width:20%; 
  margin:5px; 
  border: thin solid #ccc; 
}

JavaScript

class MyCanvas {
  constructor(width, height) {
  	this.leftPadding = 4;
    this.topPadding = 4;
    this.rightPadding = 4;
    this.bottomPadding = 4;
    this.yOffset = 10;
    
    // the right and bottom padding are special,
    // they need to take into account their oppposite padding
    this.rightPadding += this.leftPadding;
    this.bottomPadding += this.topPadding;
    
  	this.width = width || 128;
    this.height = height || 128;
    
    // new up the canvas
    this.canvas = document.createElement('canvas');
    this.canvas.height = this.height;
    this.canvas.width = this.width;
    
    // ctx is your 2d canvas that you use to draw lines, circles, fill, etc.
    this.ctx = this.canvas.getContext('2d');
  }
  
  // draws shapes using 2d coordinates
  drawShapeTemplate(shapeTemplateCoords, drawShapeWithOutlines) {
  	// if you want shapes to have outlines or not
  	drawShapeWithOutlines = drawShapeWithOutlines || false;	// default to false
    
  	// analyze the passed in shape template and the canvas will resize
    // to always fit any size shape
  	this.setCanvasBounds(shapeTemplateCoords);
    
    // always clear the canvas before drawing a new shape
    // as we are using the same canvas
    this.clearCanvas();
    
    // safer to leave it on then to turn it off
    // in case someone decides to play with translating and scaling or rotating
    // the canvas
    this.restoreCTX();
    
    // maybe use css for border around the image instead
    //this.addCanvasBorder();
  	var ctx = this.ctx;
    
    //ctx.scale(.4,.4);		// if ever you need to scale a drawn image up or down
    //ctx.translate(0,0);	// if ever you need to offset or shift the canvas
    
    // the paint brush color and size and settings
    ctx.beginPath();	// comes first before moveTo
    
    // amount of left and top padding you want to draw
    // currently right and bottom padding is lives in setCanvasBounds()
    // but can be re-visited
    //var leftPadding = 10;
 ...