简体   繁体   中英

How to add shapes to the canvas?

I want to

  • add rect shapes to each canvas which holds the current page pdf
  • shapes can be n number of times in each page.

Problem

  • Why is my shapes replacing the pdf too?
  • not able to add rect shapes to each canvas which holds the current page pdf

Below is somewhat what i have tried. https://jsfiddle.net/goteL3hn/

Code:

// Adding a rectangle
jQuery(function($) {

    $("#addRectangle").click(function() {
    fCanvas = new fabric.Canvas("the-canvas", {
        selection: false
    });
        fCanvas.add(new fabric.Rect({
            left: 100,
            top: 100,
            fill: 'red',
            width: 20,
            height: 20
        }));
    });
});

You were rendering PDF in canvas the-canvas element, but while adding rect object you used the same element to create fabricjs canvas the-canvas element, so it cleared the canvas and drawn only rect object.

You need to render the pdf page data in fabricjs canvas top context and after image loaded add that as an image object in lower canvas element.

DEMO

 // If absolute URL from the remote server is provided, configure the CORS // header on that server. var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf'; // Loaded via <script> tag, create shortcut to access PDF.js exports. var pdfjsLib = window['pdfjs-dist/build/pdf']; // The workerSrc property shall be specified. pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js'; var pdfDoc = null, pageNum = 1, prevPageNum = 1, pageRendering = false, pageNumPending = null, scale = 0.8, fCanvas = new fabric.Canvas("the-canvas", { selection: false }); /** * Get page info from document, resize canvas accordingly, and render page. * @param num Page number. */ var pageHistory = {}; function renderPage(num) { pageHistory[prevPageNum] = fCanvas.toJSON(); var jsonData = pageHistory[num]; fCanvas.discardActiveObject(); //if you have any object selected, then it will deselect if (jsonData) { fCanvas.loadFromJSON(jsonData, function() { renderPdfData(num); fCanvas.renderAll.bind(fCanvas) }); } else { pageHistory[num] = fCanvas.toJSON(); fCanvas.clear(); renderPdfData(num); } } function renderPdfData(num) { pageRendering = true; // Using promise to fetch the page pdfDoc.getPage(num).then(function(page) { var viewport = page.getViewport(scale); fCanvas.setDimensions({ height: viewport.height, width: viewport.width }) // Render PDF page into canvas context, use fabricjs top canvas element context var renderContext = { canvasContext: fCanvas.contextTop, viewport: viewport }; var renderTask = page.render(renderContext); // Wait for rendering to finish renderTask.promise.then(function() { pageRendering = false; var imageData = fCanvas.upperCanvasEl.toDataURL(); //create an image from top context and put it in lower canvas element fabric.Image.fromURL(imageData, function(img) { img.set({ left: 0, top: 0, evented: false, selectable: false, excludeFromExport:true }); fCanvas.add(img).sendToBack(img); fCanvas.clearContext(fCanvas.contextTop); if (pageNumPending !== null) { // New page rendering is pending renderPage(pageNumPending); pageNumPending = null; } }); }); }); // Update page counters document.getElementById('page_num').textContent = num; } /** * If another page rendering in progress, waits until the rendering is * finised. Otherwise, executes rendering immediately. */ function queueRenderPage(num) { if (pageRendering) { pageNumPending = num; } else { renderPage(num); } } /** * Displays previous page. */ function onPrevPage() { if (pageNum <= 1) { return; } prevPageNum = pageNum; pageNum--; queueRenderPage(pageNum); } document.getElementById('prev').addEventListener('click', onPrevPage); /** * Displays next page. */ function onNextPage() { if (pageNum >= pdfDoc.numPages) { return; } prevPageNum = pageNum; pageNum++; queueRenderPage(pageNum); } document.getElementById('next').addEventListener('click', onNextPage); /** * Asynchronously downloads PDF. */ pdfjsLib.getDocument(url).then(function(pdfDoc_) { pdfDoc = pdfDoc_; document.getElementById('page_count').textContent = pdfDoc.numPages; // Initial/first page rendering renderPage(pageNum); }); // Adding a rectangle jQuery(function($) { $("#addRectangle").click(function() { fCanvas.add(new fabric.Rect({ left: 100, top: 100, fill: 'red', width: 20, height: 20 })); }); });
 #the-canvas { border:1px solid black; }
 <script src="//mozilla.github.io/pdf.js/build/pdf.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script> <h1>PDF.js Previous/Next example</h1> <div> <input type="button" id="addRectangle" value="Add Signature"> <button id="prev">Previous</button> <button id="next">Next</button> &nbsp; &nbsp; <span>Page: <span id="page_num"></span> / <span id="page_count"></span></span> </div> <canvas id="the-canvas"></canvas>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM