var ctx = document.querySelector("canvas").getContext("2d"),
btn = document.querySelector("button"),
w = ctx.canvas.width,
h = ctx.canvas.height,
img = new Image();
img.crossOrigin = ""; img.onload = plot; img.src = "//i.imgur.com/lfsyAEc.png";
btn.onclick = plot;
function plot() {
var iw = img.width, ih = img.height,
x = Math.random() * (w - iw * 0.5), y = Math.random() * (h - ih * 0.5),
s = (Math.random() * 30 - 15)|0;
ctx.clearRect(0, 0, w, h);
ctx.translate(x, y);
ctx.rotate(Math.random() * Math.PI - Math.PI * 0.5);
ctx.drawImage(img, -(iw + s) * 0.5, -(ih + s) * 0.5, iw + s, ih + s);
ctx.setTransform(1,0,0,1,0,0);
analyze();
}
function analyze() {
var data = new Uint32Array(ctx.getImageData(0, 0, w, h).data.buffer),
len = data.length,
x, y, y1, y2, x1 = w, x2 = 0;
// y1
for(y = 0; y < h; y++) {
for(x = 0; x < w; x++) {
if (data[y * w + x] & 0xff000000) {
y1 = y;
y = h;
break;
}
}
}
//todo y1 and the others can be undefined if no pixel is found.
// y2
for(y = h - 1; y > y1; y--) {
for(x = 0; x < w; x++) {
if (data[y * w + x] & 0xff000000) {
y2 = y;
y = 0;
break;
}
}
}
// x1
for(y = y1; y < y2; y++) {
for(x = 0; x < w; x++) {
if (x < x1 && data[y * w + x] & 0xff000000) {
x1 = x;
break;
}
}
}
// x2
for(y = y1; y < y2; y++) {
for(x = w - 1; x > x1; x--) {
if (x > x2 && data[y * w + x] & 0xff000000) {
x2 = x;
break;
}
}
}
// mark area:
ctx.strokeStyle = "hsl(" + (360 * Math.random()) + ", 80%, 50%)";
ctx.strokeRect(x1 + 0.5, y1 + 0.5, x2 - x1, y2 - y1);
}
body {background:#aaa;margin:1px 0}
canvas {border:1px solid #777; background:#f0f0f2}
<button>Again</button><br>
<canvas width=640 height=165></canvas>