Printing fabricjs canvas on desktop and mobile devices?

自作多情 提交于 2019-12-11 07:27:56

问题


I'm using the following to print on my canvas from my laptop which works great (kudos user700284) but when I try to use the functionality on a tablet or mobile it doesn't work. When I click the button, a new tab opens and closes immediately (this is on mobile / tablet). What might I do to enable printing on all mediums?

function printCanvas() {
    var dataUrl = document.getElementById('c').toDataURL(); //attempt to save base64 string to server using this var  
    var windowContent = '<!DOCTYPE html>';
    windowContent += '<html>'
    windowContent += '<head><title>Print canvas</title></head>';
    windowContent += '<body>'
    windowContent += '<img src="' + dataUrl + '" onload=window.print();window.close();>';
    windowContent += '</body>';
    windowContent += '</html>';
    var printWin = window.open('', '', 'width=340,height=260');
    printWin.document.open();
    printWin.document.write(windowContent);
}

<button onclick="printCanvas()">Print</button>

回答1:


You can download as pdf using html2canvas and jspdf.

DEMO

var canvas = new fabric.Canvas('a',{backgroundColor :'powderblue'});
canvas.add(new fabric.Text('FabricJS is Awsome',{
 left:50,
 top:50
}));

function downloadCanvas(){
  canvas.discardActiveObject();
  canvas.renderAll();
  html2canvas(document.getElementById('a'), {
    onrendered: function(canvas) {         
      var imgData = canvas.toDataURL('image/png');         
      var doc = new jsPDF('p', 'mm');
      doc.addImage(imgData, 'PNG', 0, 0);
      doc.save('test.pdf');
    }
  });
}
canvas {
  border: 2px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<button onclick='downloadCanvas()'>Download</button>
<canvas id="a" width="500" height="250"></canvas>



回答2:


I may be wrong but what about the simple way to do it:

create a css file with media queries

@media print { 
// hide everything
  * {
    display: none;
  }
// add display block to your canvas only
  #c {
    display: block
  }
}

Then printing your current app page should print just the canvas.



来源:https://stackoverflow.com/questions/47368260/printing-fabricjs-canvas-on-desktop-and-mobile-devices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!