JSFiddle - React, Tailwind, and code Playground
by tinyhustlee
HTML
<h4>Original Image</h4>
<img src="https://dl.dropboxusercontent.com/u/139992952/multple/makeIndividual.png">
<h4>Canvas with sticker effect applied</h4>
<canvas id="canvas" width=300 height=300></canvas><br>
<h4>Each discrete element of the image is processed on a separate canvas<br>Temp-canvases are shown below for illustration purposes only.</h4>
CSS
body {
background-color:silver;
}
canvas {
border:1px solid red;
}
JavaScript
// canvas related variables
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// variables used in pixel manipulation
var canvases = [];
var imageData, data, imageData1, data1;
// size of sticker outline
var strokeWeight = 8;
// true/false function used by the edge detection method
var defineNonTransparent = function (x, y) {
return (data1[(y * cw + x) * 4 + 3] > 0);
}
// the image receiving the sticker effect
var img = new Image();
img.crossOrigin = "anonymous";
img.onload = start;
img.src = "https://cloudinary-res.cloudinary.com/image/upload/c_scale,f_auto,q_auto/v1554826118/website/customers/0.jpg";
//img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/angryBirds.png";
function start() {
// resize the main canvas to the image size
canvas.width = cw = img.width;
canvas.height = ch = img.height;
// draw the image on the main canvas
ctx.drawImage(img, 0, 0);
// Move every discrete element from the main canvas to a separate canvas
// The sticker effect is applied individually to each discrete element and
// is done on a separate canvas for each discrete element
while (moveDiscreteElementToNewCanvas()) {}
// add the sticker effect to all discrete elements (each canvas)
for (var i = 0; i < canvases.length; i++) {
addStickerEffect(canvases[i], strokeWeight);
ctx.drawImage(canvases[i], 0, 0);
}
// redraw the original image
// (necessary because the sticker effect
// slightly intrudes on the discrete elements)
ctx.drawImage(img, 0, 0);
}
//
function addStickerEffect(canvas, strokeWeight) {
var url = canvas.toDataURL();
var ctx1 = canvas.getContext("2d");
var pts = canvas.outlinePoints;
addStickerLayer(ctx1, pts, strokeWeight);
var imgx = new Image();
imgx.onload = function () {
ctx1.drawImage(imgx, 0, 0);
}
imgx.src = url;
}
function addStickerLayer(context, points, weight) {
...