JSFiddle - React, Tailwind, and code Playground
by vijayweb
HTML
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<canvas id="collage" width="920" height="480"></canvas>
<div id="savememe" class="btn btn-primary">Save</div>
JavaScript
//CANVAS SIZE
micanvas = document.getElementById('collage');
ww = micanvas.width;
wh = micanvas.height;
ctx2 = micanvas.getContext('2d');
ctx2.font="italic 176px Times";
ctx2.strokeText("Italic, Stroke, Text, 76px, times", 20, 85);
$(function() {
$("#savememe").click(function() {
//WE GET ALL CANVAS PIXELDATA
imageData = ctx2.getImageData(0, 0, ww, wh);
/* WE INITIALIZE THE VARIABLES WHERE WE'LL STORE THE DIMENSIONS
OF THE CANVAS RECTANGLE WE HAVE RELEVANT DATA, IE NON-EMPTY
PIXELS*/
/* WE INICIALIZE TOP LEFT CORNER FAR IN THE RIGHT SIDE */
var topLeftCorner = {};
topLeftCorner.x = 9999;
topLeftCorner.y = 9999;
/* WE INICIALIZE BOTTOM LEFT CORNER OUTSIDE THE CANVAS
BELOW WE'LL SEE WHY :) */
var bottomRightCorner = {};
bottomRightCorner.x = -1;
bottomRightCorner.y = -1;
/* NOW WE RUN TROUGHT ALL THE IMAGES'S PIXELS CHECKING IF THERE IS SOTHING ON THEM */
for (y = 0; y < wh; y++) {
for (x = 0; x < ww; x++) {
var pixelPosition = (x * 4) + (y * wh * 4);
/* EACH PIXEL HAS 4 "BYTES" OF DATA CORRESPONDING TO red, green, blue AND alpha*/
//r = imageData.data[pixelPosition]; //red
//g = imageData.data[pixelPosition+1]; //green
//b = imageData.data[pixelPosition+2]; //blue
/* I'M ONLY INTERESTED IN ALPHA COMPONENT, IF SOMETHING IS PRESENT IN THAT PIXEL ALPHA (a) VALUE MUST BE > 0*/
a = imageData.data[pixelPosition+3]; //alpha
/* I IGNORE THE r,g,b COMPONENT, ONLY CHECK IF alpha > 0 */
if (a > 0) {
/* HERE I GET THE TOP MOST LEFT PIXEL, AND THE BOTTOM MOST RIGHT ONE */
if (x < topLeftCorner.x) {
topLeftCorner.x = x;
}
if (y < topLeftCorner.y) {
topLeftCorner.y = y;
}
if (x > bottomRightCorner.x) {
bottomRightCorner.x = x;
}
if (y > bottomRightCorner.y) {
bottomRightCorner.y = y;
}
}
}
}
/* HERE WE HAVE THE COORDINATES OF THE RECTANGLE CONTAINING SOMETHING DROWN */
console.log(topLeftCorner);
console.log(bottomRightCorner);
/* NOW WE SAVE THE REGION WE WANT TO TRIM TO A VARIABLE */
/* (x, y, width, heigth) */
relevantData = ctx2.getImageData(topLeftCorner.x,...