Kiran Kiran - 1 year ago 151
Javascript Question

not able to draw rect on existing <canvas> which rendered PDF using pdfjs


Have a canvas in your page

<canvas id="pdfCanvas">

create a fabric canvas for existing canvas
new fabric.Canvas("pdfCanvas");

have mouse.down, mouse.up, mouse.move methods to enable drawing rectangles
render pdf in the above canvas "pdfCanvas" using PDF.js
browser now shows the rendered PDF
now draw rectangles on the pdf, it hides the rendered canvas but it does draw objects


Here is the fiddle to see the issue:
- run the above
- you can see the fabric rectangle is hiding behind the rendered pdf
- click on the pdf canvas area to see the fabric objects

Answer Source

What I see from your fiddle is that you don't wait the result of page.render method, which is asyncronous, then, unfortunately, if you wait the page.render, the fabric.canvas instance will clean your previously filled canvas, and we can't do nothing for this. So I tried another approach: First of all, I wait the pdf.js page.render method, then I invoke the .toDataURL of your previously filled canvas so that I can have a copy to the old content, then I set your previously filled canvas as background of your new fabric.canvas and finally I draw your rectangle.

var url = '';
var canvas = document.getElementById('pdfcanvas');
var context = canvas.getContext('2d');
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(function(pdf) {
  pdf.getPage(1).then(function(page) {
    var scale = 1.5;
    var viewport = page.getViewport(scale);
    canvas.height = viewport.height;
    canvas.width = viewport.width;
      canvasContext: context,
      viewport: viewport
    }).then(function() {

      var bg = canvas.toDataURL("image/png");
      var fcanvas = new fabric.Canvas("pdfcanvas", {
        selection: false
      var rect = new fabric.Rect({
        left: 100,
        top: 100,
        width: 50,
        height: 50,
        fill: '#FF454F',
        opacity: 0.5,
        transparentCorners: true,
        borderColor: "gray",
        cornerColor: "gray",
        cornerSize: 5
<script src=""></script>
<script src=""></script>
<canvas id="pdfcanvas" style="border:1px solid black"></canvas>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download