Thursday, 20 April 2023

How can I prevent loss of quality and darkening when merging two canvases that load PDFs in JavaScript?

I am trying to merge two canvases, each of which contains an identical PDF document except for a signature pad. My goal is to combine both canvases to merge the signature pads into one document. However, when I combine the canvases, I notice that the resulting document loses quality and the background becomes darker.

Here is the code I am using to merge the canvases:

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';
}



from How can I prevent loss of quality and darkening when merging two canvases that load PDFs in JavaScript?

No comments:

Post a Comment