JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<button id="stroke">Path.stroke</button>
<br>
<button id="erase">Erase main canvas</button>
<br>
<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");

function Path(maxWidth, maxHeight, color, linewidth, drawingContext) {
    this.width = maxWidth;
    this.height = maxHeight;
    this.drawingCtx = drawingContext;
    this.points = []
    this.canvas = document.createElement("canvas");
    this.canvas.width = maxWidth;
    this.canvas.height = maxHeight;
    this.ctx = this.canvas.getContext("2d");
    this.ctx.strokeStyle = color;
    this.ctx.lineWidth = linewidth;
    this.lastX;
    this.lastY;
}
Path.prototype.moveTo = function (x, y) {
    this.lastX = x;
    this.lastY = y;

}
Path.prototype.lineTo = function (x, y) {
    this.ctx.moveTo(this.lastX, this.lastY);
    this.ctx.lineTo(x, y);
    this.ctx.stroke();
    this.lastX = x;
    this.lastY = y;
}
Path.prototype.stroke = function () {
    this.drawingCtx.drawImage(this.canvas, 0, 0);
}

var p = new Path(300, 300, "blue", 2, ctx);
p.moveTo(69, 91);
p.lineTo(250, 150);
p.moveTo(69, 208);
p.lineTo(180, 54);
p.lineTo(180, 245);
p.lineTo(69, 91);
p.moveTo(69, 208);
p.lineTo(250, 150);
p.stroke();

$("#stroke").click(function () {
    p.stroke();
});
$("#erase").click(function () {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
});