print image using javascript

Viewed 76

I have a <canvas> and I want to show the printing dialog box to allow the user to print the image, but it keeps throwing the following error:

Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

The convert HTML to image, the image appears on the page.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = "<svg xmlns='http://www.w3.org/2000/svg' width='400' height='1500'>" +
    "<foreignObject width='100%' height='100%'>" + jQuery("#mytable").html() +
      "<style>" +
        "table {background-color:#fff;}" +
        ".table1canvas {border: 2px solid black;" +
        "border-bottom-width:1px;}" +
        ".table2canvas {border: 2px solid black;" +
        "border-bottom-width:1px;" +
        "border-top-width:0px;}" +
        ".table3canvas {border: 2px solid black;}" +
        ".table4canvas {border: 2px solid black;" +
        "border-bottom-width:1px;" +
        "border-top-width:0px;}" +
      "</style>" +
    "</foreignObject>" +
  "</svg>";

var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([data], {
  type: "image/svg+xml;charset=utf-8"
});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
  ctx.drawImage(img, 0, 0);
  DOMURL.revokeObjectURL(url);
};
img.src = url;

jQuery(document).on('click', '#printmeB', function(e) {
  btnclick();
  e.preventDefault();
});

function btnclick() {
  var canvass = document.getElementById("canvas");
  image = canvass.toDataURL("image/png", 1.0).replace("image/png", "image/octet-stream");
  var link = document.createElement('a');
  link.download = "my-image.png";
  link.href = image;
  link.click();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="canvas"></canvas>

0 Answers
Related