Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically Crop HTML5 canvas to contents

Let's say this is my canvas, with an evil-looking face drawn on it. I want to use toDataURL() to export my evil face as a PNG; however, the whole canvas is rasterised, including the 'whitespace' between the evil face and canvas edges.

+---------------+ |               | |               | |     (.Y. )    | |      /_       | |     \____/    | |               | |               | +---------------+ 

What is the best way to crop/trim/shrinkwrap my canvas to its contents, so my PNG is no larger than the face's 'bounding-box', like below? The best way seems to be scaling the canvas, but supposing the contents are dynamic...? I'm sure there should be a simple solution to this, but it's escaping me, with much Googling.

+------+ |(.Y. )| | /_   | |\____/| +------+ 

Thanks!

like image 599
c24w Avatar asked Aug 03 '12 13:08

c24w


People also ask

How do I make my canvas fit the screen in HTML?

to set the canvas's width and height both to 100%. We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen. Also, we make the html and body elements fill the screen by setting the width and height to 100%.

How do I make a canvas take up the whole page?

Code to make canvas occupy full page :innerWidth; canvas. height = window. innerHeight; //Done! Enjoy full page canvas!

Does HTML5 support canvas element?

The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images.


1 Answers

Edited (see comments)

function cropImageFromCanvas(ctx) {   var canvas = ctx.canvas,      w = canvas.width, h = canvas.height,     pix = {x:[], y:[]},     imageData = ctx.getImageData(0,0,canvas.width,canvas.height),     x, y, index;    for (y = 0; y < h; y++) {     for (x = 0; x < w; x++) {       index = (y * w + x) * 4;       if (imageData.data[index+3] > 0) {         pix.x.push(x);         pix.y.push(y);       }      }   }   pix.x.sort(function(a,b){return a-b});   pix.y.sort(function(a,b){return a-b});   var n = pix.x.length-1;    w = 1 + pix.x[n] - pix.x[0];   h = 1 + pix.y[n] - pix.y[0];   var cut = ctx.getImageData(pix.x[0], pix.y[0], w, h);    canvas.width = w;   canvas.height = h;   ctx.putImageData(cut, 0, 0);    var image = canvas.toDataURL();  //open cropped image in a new window   var win=window.open(image, '_blank');   win.focus(); } 
like image 158
potomek Avatar answered Oct 14 '22 05:10

potomek