JSFiddle - React, Tailwind, and code Playground

by Ivan Shukshin

HTML

<canvas width=400 height=400 id="canvas"></canvas>
<br>
<button id="print">
print
</button>

JavaScript

var canvas = document.getElementById('canvas');

var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;

context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();

context.beginPath();
context.arc(300, 300, 50, 0, 2 * Math.PI, false);
context.fillStyle = 'red';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#000000';
context.stroke();

document.getElementById('print').addEventListener('click', function(){
  printCanvas();
});


function emptyPixel(context, x, y) {
  var p = context.getImageData(x, y, 1, 1).data; 
  if(!p[0] && !p[1] && !p[2] && !p[3]) {
    return true;
  }
  return false;
}

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};
}

function printCanvas()  
{  

  var padding = 10; // padding around found objects
  
  // find borders of a rectange covering all objects
  var borders = getCanvasBorders(canvas);
  var newWidth = borders.botright.x - borders.topleft.x;
  var newHeight = borders.botright.y - borders.topleft.y;
  
  // create a new canvas
  var newcanvas = document.createElement('canvas');
  newcanvas.width = newWidth + 2 * padding;
  newcanvas.height = newHeight + 2 * padding;
  var newcontext =...