JSFiddle - React, Tailwind, and code Playground

by m1erickson

HTML

<p>A rect predrawn on a canvas</p>
<canvas id="canvas" width=50 height=50></canvas>
<p>An image of just the rect clipped from the canvas above</p>
<img id="clipped" width=28 height=28>
<p>An image of just a rect created on a temp canvas</p>
<img id="drawn" width=26 height=26>

CSS

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

JavaScript

// draw a rect on a canvas 
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(20, 20, 26, 26);
ctx.fillStyle = "orange";
ctx.strokeStyle = "blue";
ctx.fill();
ctx.lineWidth = 1;
ctx.stroke();

// clip the rect out of the canvas and save as an image
var tempcanvas = document.createElement("canvas");
var tempctx = tempcanvas.getContext("2d");
tempcanvas.width = 28;
tempcanvas.height = 28;
tempctx.drawImage(canvas, 19, 19, 28, 28, 0, 0, 28, 28);
document.getElementById("clipped").src = tempcanvas.toDataURL();

// create a new rect on a temp canvas and save as an image
var tempcanvas1 = document.createElement("canvas");
var tempctx1 = tempcanvas1.getContext("2d");
tempcanvas1.width = 28;
tempcanvas1.height = 28;

tempctx1.beginPath();
tempctx1.rect(0, 0, 26, 26);
tempctx1.fillStyle = "orange";
tempctx1.strokeStyle = "lightgray";
tempctx1.fill();
tempctx1.lineWidth = 1;
tempctx1.stroke();
document.getElementById("drawn").src = tempcanvas.toDataURL();