Print html5 canvas section

I have html5 canvas (3000px x 3000px). I use 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 that if I only have an element on the canvas (let's say a circle) and click print, it will try to print the entire canvas (3000 x 3000). Is there a way to change it, so it prints only a certain section of the canvas or only the part where there are elements, and not print empty space.

Thank.

+4
source share
2 answers

Another answer describes the correct approach. The main problem is to find boundaries. I get all the image data and in two borders for the search:

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 document, jsfiddle.

+3

, , :

  • ,
  • , , drawImage() , -x -y .

.

: , , . .

+1

Source: https://habr.com/ru/post/1670109/


All Articles