合并两个在 JavaScript 中加载 PDF 的画布时,如何防止质量下降和变暗?

问题描述 投票:0回答:1

我正在尝试合并两个画布,每个画布都包含一个相同的 PDF 文档,除了签名板。我的目标是将两个画布结合起来,将签名板合并到一个文档中。但是,当我组合画布时,我注意到生成的文档质量下降并且背景变暗。

这是我用来合并画布的代码:

async function combinePages(numPages) {
  console.log("Combining ..."+numPages);

  let canvas1, canvas2; // Declare canvas1 and canvas2 variables here

  // Iterate through each page
  for (let i = 1; i <= numPages; i++) {
  
    let element = document.getElementById(`canvasContainer3_${i}`);
    if (!element) {
      // Create a new canvas container element
      let container = document.createElement("div");
      container.id = `canvasContainer3_${i}`;
      // Append the container to the document body
      document.body.appendChild(container);
    }
    
    // Get the canvas elements for the current page
    canvas1 = document.getElementById('canvas1_'+i);
    canvas2 = document.getElementById('canvas2_'+i);
    
    // Create a new canvas element for the combined page
    let combinedCanvas = "";
    combinedCanvas = document.createElement("canvas");
    combinedCanvas.setAttribute('id', 'canvas3_'+i);
    
    let canvas1Width = canvas1.width;
    let canvas1Height = canvas1.height;
    let canvas2Width = canvas2.width;
    let canvas2Height = canvas2.height;

    // Set the size of the combined canvas
    combinedCanvas.width = Math.max(canvas1Width, canvas2Width);
    combinedCanvas.height = Math.max(canvas1Height, canvas2Height);

    let context = combinedCanvas.getContext("2d");
    
    context.drawImage(canvas1, 0, 0);
    
    // Draw the contents of the second canvas onto the combined canvas
    context.globalCompositeOperation = 'multiply';

    context.drawImage(canvas2, 0, 0);
   
    // Add the combined canvas to the page
    let container = document.getElementById(`canvasContainer3_${i}`);
    container.appendChild(combinedCanvas);

    document.getElementById("wrapper").appendChild(container);

    // Hide canvas1 and canvas2
   //canvas1.style.display = "none";
   // canvas2.style.display = "none";
  }
 
  return 'finish combination';
}

这里是我使用的 PDF 示例:

PDF 1 与 PDF 2 合并,然后结果与 PDF 3 合并,然后该结果与 PDF 4 合并。

这是我得到的结果:

白色背景是灰色的,颜色是深色的。

javascript merge html5-canvas pdf-lib.js
1个回答
1
投票

问题是您正在使用的 globalCompositeOperation。

使用“乘法”,顾名思义,顶层的像素与底层的相应像素相乘。所以结果是一张更暗的照片。

如果您希望两层结合而不变暗,请使用不同的 globalCompositeOperation,例如默认的“source-over”。

例如

// Draw the contents of the second canvas onto the combined canvas
context.globalCompositeOperation = 'source-over';

您可以在此处查看各种 globalCompositeOperation 操作的输出。 https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation

© www.soinside.com 2019 - 2024. All rights reserved.