JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<h4>Using context.translate(centerX,centerY)<br>the Polygon is drawn center-canvas<br>
plus its 5,5 starting point.
</h4>

<canvas id="canvas" width=300 height=300></canvas>

CSS

body{ background-color: ivory; }
canvas{border:1px solid red;}

JavaScript

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


// calculate the middle of the canvas
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;

// just for testing: draw crosshairs on center canvas
ctx.beginPath();
ctx.moveTo(centerX, 0);
ctx.lineTo(centerX, canvas.height);
ctx.moveTo(0, centerY);
ctx.lineTo(canvas.width, centerY);
ctx.stroke();

// define some points for your polygon
var poly = [5, 5, 100, 50, 50, 100, 10, 90];

// save the canvas context in its untranslated state
ctx.save();

// translate the canvas
// the context now uses centerX,centerY as its 0,0 origin
ctx.translate(centerX-50, centerY-50);

// draw the polygon
ctx.beginPath();
ctx.moveTo(poly[0], poly[1]);
for (var i = 2; i < poly.length; i += 2) {
    ctx.lineTo(poly[i], poly[i + 1])
}
ctx.closePath();
ctx.fillStyle = '#f00';
ctx.fill();

// restore the context to its untranslated state
// (otherwise all further drawings will be "moved"
// just like this polygon
ctx.restore();