Почему, при печати, canvas очищается, и больше на нём ничего не появляется?

При нажатии на кнопку "create rectangle", должен появляться квадрат, но почему, после нажатия на кнопку "print", этого не происходит?

var canvas = document.getElementById("printable-area");
var ctx = canvas.getContext('2d')

function createRectangle() {
    ctx.fillRect(200, 200, 100, 100);
}

ctx.fillRect(200, 200, 100, 100);

function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;
}
#printable-area {
    border: 2px dotted #aaa
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
      <canvas width="500" height="500" id="printable-area"></canvas>
      <input type="button" onclick="printDiv('printable-area')" value="print"/>
      <input type="button" onclick="createRectangle()" value="create rectangle"/>
    <script src="script.js"></script>
  </body>
</html>


Ответы (1 шт):

Автор решения: UModeL

"Грязный хак" - просто скрыть лишнее:

var canvas = document.getElementById("printable-area");
var ctx = canvas.getContext('2d')

ctx.fillStyle = 'red'; ctx.fillRect(100, 100, 170, 170);
ctx.fillStyle = 'blue'; ctx.beginPath();
ctx.ellipse(350, 180, 100, 100, Math.PI / 2, 0, 2 * Math.PI);
ctx.fill();

function createRectangle() {
  ctx.fillStyle = 'green'; ctx.fillRect(200, 200, 100, 100);
}

function printDiv() {
  document.body.className = 'print';
  window.print();
  document.body.className = '';
}
#printable-area { border: 2px dotted #aaa; }

body.print #printable-area { border: 2px dotted #aaa0; }
body.print *:not(#printable-area) { display: none; }
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <input type="button" onclick="printDiv()" value="print" />
  <input type="button" onclick="createRectangle()" value="create rectangle" />
  <h1>Печать</h1>
  <canvas width="500" height="500" id="printable-area"></canvas>
  <script src="script.js"></script>
</body>

</html>

→ Ссылка