JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<canvas id="contour" width="100" height="100"></canvas>
<p>Image source: <a href="http://www.lietuvoszemelapis.com/wp-content/uploads/2016/09/lietuvos-apskritys.jpg" target="_blank">greyamoon</a>
</p>
<script src="app.js" charset="utf-8"></script>
</body>
JavaScript
"use strict";
function everyPixel(ctx, f) {
var imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
var data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
f(data, i);
}
ctx.putImageData(imageData, 0, 0);
}
/*
* Constructor for the image processing parts.
* @param imgctx 2d canvas to draw the contour image.
* @param ctx 3d canvas for the drawing canvas (the colours).
* @param url The URL of the contour image.
*/
var Drawing = function (imgctx, url) {
this.imgctx = imgctx;
this.url = url;
this.threshold = 200;
/* Draws the contour on imgctx. Makes sure it's just black and white.
* @param img The image to draw. If undefined, it uses this.image.
*/
this.drawContour = function (img) {
if (img === undefined) {
img = this.image;
}
// clear everything
this.imgctx.clearRect(0, 0, this.imgctx.width, this.imgctx.height);
// draw the image
this.imgctx.drawImage(img, 0, 0);
// process pixel by pixel
var that = this;
var timeBefore = new Date().getTime();
console.log("threshold is", this.threshold);
everyPixel(imgctx, function (data, index) {
// my image is not transparent initially,
// so not filtering on alpha at all.
if (data[index] < that.threshold && data[index + 1] < that.threshold && data[index + 2] < that.threshold) {
// make black
data[index] = 0;
data[index + 1] = 0;
data[index + 2] = 0;
data[index + 3] = 255;
} else {
// make transparent
data[index] = 0;
data[index + 1] = 0;
data[index + 2] = 0;
data[index + 3] = 0;
}
});
console.log("processing done", (new Date().getTime()) - timeBefore, "ms");
};
this.imageLoaded...