如何在画布上添加形状?

时间:2018-12-27 23:44:39

标签: javascript html5-canvas fabricjs pdfjs

我想

  • 向包含当前页面pdf的每个画布添加矩形形状
  • 形状在每个页面中可以是n次。

问题

  • 为什么我的形状也替换了pdf?
  • 无法向包含当前页面pdf的每个画布添加矩形形状

以下是我尝试过的内容。 https://jsfiddle.net/goteL3hn/

代码:

// 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
        }));
    });
});

1 个答案:

答案 0 :(得分:1)

您正在画布the-canvas元素中呈现PDF,但是在添加rect对象时,您使用相同的元素来创建fabricjs画布the-canvas元素,因此它清除了画布并仅绘制了rect对象。

您需要在fabricjs画布顶部上下文中呈现pdf页面数据,并在加载图像后将其添加为下部画布元素中的图像对象。

演示

// 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>