JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
<input type="checkbox" id="showImage" />Show Image
<br>
<input type="checkbox" id="showOutline" />Show Outline Path
<br>
<canvas id="canvas" width=150 height=150></canvas>
CSS
body {
background-color: ivory;
}
canvas {
border:1px solid red;
}
JavaScript
// canvas related variables
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
// checkbox to show/hide the original image
var $showImage = $("#showImage");
$showImage.prop('checked', true);
// checkbox to show/hide the path outline
var $showOutline = $("#showOutline");
$showOutline.prop('checked', true);
// 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;
$showImage.change(function () {
redraw();
});
$showOutline.change(function () {
redraw();
});
redraw();
}
img.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/sun.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
if ($showImage.is(':checked')) {
ctx.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2);
...