JSFiddle - React, Tailwind, and code Playground

by Bladetrick

HTML

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

CSS

canvas { border: 1px solid purple; }

JavaScript

// canvas related variables
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;


// an array of points that defines the outline path
var points;

// pixel data of this image for the defineNonTransparent 
// function to use
var imgData, data;

// This is used by the marching ants algorithm
// to determine the outline of the non-transparent
// pixels on the image
var defineNonTransparent = function (x, y) {
    var a = data[(y * cw + x) * 4 + 3];
    return (a > 20);
}

// load the image
var img = new Image();
img.crossOrigin = "anonymous";
img.onload = function () {

    // draw the image
    // (this time to grab the image's pixel data
    ctx.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2);

    // grab the image's pixel data
    imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    data = imgData.data;

    // call the marching ants algorithm
    // to get the outline path of the image
    // (outline=outside path of transparent pixels
    points = geom.contour(defineNonTransparent);

    ctx.strokeStyle = "red";
    ctx.lineWidth = 2;

    redraw();

}
img.src = "https://cdn1.iconfinder.com/data/icons/shield-4/744/1-512.png";

// redraw the canvas
// user determines if original-image or outline path or both are visible
function redraw() {

    // clear the canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // draw the image   
        //ctx.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2);
   

    // draw the path (consisting of connected points)    
        // draw outline path
        ctx.beginPath();
        ctx.moveTo(points[0][0], points[0][1]);
        for (var i = 1; i < points.length; i++) {
            var point = points[i];
            ctx.lineTo(point[0], point[1]);
        }
        ctx.closePath();
        ctx.stroke();
        
ctx.save();       ...