Skip to main content

Usage Tips

html2canvas element alignment fix

When using html2canvas, elements may misalign compared to browser rendering. The problem: html2canvas element alignment differs from actual browser rendering. Solution: Dynamic CSS injection Fix alignment by injecting temporary fix styles and controlling render parameters.
const exportElement = async () => {
  // 1. Inject fix styles
  const style = document.createElement('style');
  style.id = 'export-fix-style';
  document.head.appendChild(style);
  
  if (style.sheet) {
    style.sheet.insertRule('* { box-sizing: border-box !important; }', 0);
    style.sheet.insertRule('img { display: inline-block !important; }', 1);
    style.sheet.insertRule('div { box-sizing: border-box !important; line-height: 1.2 !important; }', 2);
    style.sheet.insertRule('span { line-height: 1.2 !important; }', 3);
  }
  
  try {
    // 2. Wait for resources (images + fonts)
    await Promise.all([
      ...document.images.map(img => 
        img.complete ? Promise.resolve() : new Promise(resolve => {
          img.onload = img.onerror = resolve;
        })
      ),
      document.fonts.ready // Wait for fonts to load
    ]);
    
    // 3. Capture screenshot (key config below)
    const canvas = await html2canvas(element, {
      scale: 3, // High-res scaling
      foreignObjectRendering: false, // Disable foreignObject, use traditional rendering for stability
      useCORS: true, // Allow cross-origin images
      allowTaint: true // Allow tainted canvas (works with useCORS for cross-origin)
    });
    
    return canvas.toDataURL('image/png', 1.0); // Return PNG data
  } finally {
    // 4. Clean up temporary styles (ensure removal even on errors)
    document.getElementById('export-fix-style')?.remove();
  }
};
Key configuration:
ParameterRecommended ValuePurpose
foreignObjectRenderingfalseDisable foreignObject rendering, use traditional Canvas drawing to avoid alignment issues from SVG rendering differences
box-sizingborder-boxUnified box model calculation (includes padding/border) to avoid size calculation errors from default content-box
line-height1.2Fixed line height to eliminate vertical alignment shifts from dynamic line height changes
img { display }inline-blockAvoid baseline alignment issues from img default inline element vertical-align: baseline
Notes:
  1. Configuration consistency: All export scenarios (single export, batch export) should use the same config to avoid alignment issues from different rendering logic.
  2. Wait adequately: After changing page state (dynamic content loading, style changes), wait at least 1000ms before capturing to ensure DOM and styles are fully stable.
  3. Clean up promptly: Use try...finally to ensure temporary fix styles (export-fix-style) are removed after capture to avoid polluting normal page styles.
  4. Test thoroughly: Cover “single export,” “batch export,” “complex layouts (images/text/nested elements)” to verify alignment consistency.