4

I have a html5 canvas (3000px x 3000px). I am using the following function to print the canvas:

function printCanvas()  
{  
    popup = window.open();
    popup.document.write("<br> <img src='"+canvas.toDataURL('png')+"'/>");
    popup.print();
}

The problem is, if I have only element on the canvas (say a circle) and press print, it will attempt to print out the entire canvas (3000 x 3000). Is there a way to change it so it only prints a certain section of the canvas or just the part where there are elements and not print out white space.

Thanks.

Tahmid
  • 185
  • 1
  • 4
  • 20

2 Answers2

3

The other answer describes right approach. The main problem is to find boundaries. I get all image data and in two for-loops find boundaries:

function getCanvasBorders(canvas) {
  var topleft = {x: false, y: false};
  var botright = {x: false, y: false};

  for(var x = 0; x < canvas.width; x++) {
    for(var y = 0; y < canvas.height; y++) {
      if(!emptyPixel(context, x, y)) {
        if(topleft.x === false || x < topleft.x) {
          topleft.x = x;
        }
        if(topleft.y === false || y < topleft.y) {
          topleft.y = y;
        }
        if(botright.x === false || x > botright.x) {
          botright.x = x;
        }
        if(botright.y === false || y > botright.y) {
          botright.y = y;
        }
      }
    }
  }

  return {topleft: topleft, botright: botright};
}

SO snippets can't work with document, so here is a jsfiddle.

shukshin.ivan
  • 11,075
  • 4
  • 53
  • 69
1

Assuming you have a way to track and redraw the objects, you can do the following:

  1. Calculate the max bounds that can contain all the objects
  2. Create a new canvas the size of that bound
  3. Draw in the region the bound represents using drawImage() with its clipping parameters, but offset -x and -y of the bound start position.

Print the temporary canvas instead.

Update: to find edges of image content only, assuming transparency for background, see this answer.