### Install html2canvas via npm Source: https://github.com/niklasvh/html2canvas/blob/master/docs/getting-started.md Install the html2canvas library using npm. This is the recommended way to add the library to your project for easy dependency management. ```bash npm install html2canvas ``` -------------------------------- ### Install Gatsby Starter Source: https://github.com/niklasvh/html2canvas/blob/master/www/README.md This command installs the default Gatsby starter project. Ensure Gatsby is installed globally on your system before running this command. ```bash gatsby new gatsby-example-site ``` -------------------------------- ### Import html2canvas in JavaScript Source: https://github.com/niklasvh/html2canvas/blob/master/docs/getting-started.md Import the html2canvas library into your JavaScript project after installation. This allows you to use its functionalities in your code. ```javascript import html2canvas from 'html2canvas'; ``` -------------------------------- ### Install html2canvas Dependencies using npm Source: https://github.com/niklasvh/html2canvas/blob/master/README.md This command installs the necessary dependencies for the html2canvas library using npm. It assumes you have Node.js and npm installed and are in the root directory of the cloned repository. ```bash npm install ``` -------------------------------- ### CSS Styling Examples Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/clip.html This snippet demonstrates basic CSS styling for different HTML elements. It includes examples for spans, paragraphs, divs, and the body tag. No external dependencies are required for these styles. ```css span { color:blue; } ``` ```css p { background-color: green; } ``` ```css div { background: red; border: 5px solid blue; } ``` ```css body { font-family: Arial; } ``` -------------------------------- ### Create Content Dynamically with JavaScript Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/text/underline.html This snippet demonstrates how to create content dynamically using JavaScript. It's a general example that can be adapted for various use cases. No specific libraries are required, relying on standard DOM manipulation. ```javascript // Creating content through JavaScript ``` -------------------------------- ### Customize html2canvas Rendering with Configuration Options (JavaScript) Source: https://context7.com/niklasvh/html2canvas/llms.txt Provides examples of using configuration options to customize html2canvas rendering behavior. Options cover canvas dimensions, background color, image handling (like CORS and timeouts), logging, rendering strategies, window/element dimensions, and element filtering. Dependencies: html2canvas library. ```javascript // Comprehensive configuration example html2canvas(document.querySelector('#target'), { // Canvas dimensions and positioning width: 1024, height: 768, x: 0, y: 0, scale: 2, // High DPI rendering (2x device pixel ratio) // Background color (default: #ffffff) backgroundColor: '#f0f0f0', // Use null for transparent background // backgroundColor: null, // Image handling allowTaint: false, // Allow cross-origin images to taint canvas useCORS: true, // Use CORS to load cross-origin images imageTimeout: 15000, // Image load timeout in ms (0 = no timeout) proxy: 'https://my-proxy.com/proxy', // Proxy URL for cross-origin images // Rendering options logging: true, // Enable console logging for debugging foreignObjectRendering: false, // Use SVG foreignObject if available removeContainer: true, // Clean up temporary cloned DOM // Window dimensions (affects media queries) windowWidth: window.innerWidth, windowHeight: window.innerHeight, scrollX: window.pageXOffset, scrollY: window.pageYOffset, // Element filtering ignoreElements: function(element) { // Exclude elements with specific class return element.classList.contains('no-screenshot'); }, // DOM manipulation after cloning onclone: function(clonedDoc) { // Modify cloned document before rendering clonedDoc.getElementById('sensitive-info').style.display = 'none'; } }).then(canvas => { document.body.appendChild(canvas); }); ``` -------------------------------- ### Basic HTML and CSS Setup for html2canvas Testing Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/acid2.html Defines fundamental HTML and CSS rules for the test environment, including font, margin, padding, and background properties for the html and body elements. It also includes styles for introductory messages and image placeholders. ```css html { font: 12px sans-serif; margin: 0; padding: 0; overflow: hidden; /* hides scrollbars on viewport, see 11.1.1:3 */ background: white; color: red; } body { margin: 0; padding: 0; } .intro { font: 2em sans-serif; margin: 3.5em 2em; padding: 0.5em; border: solid thin; background: white; color: black; position: relative; z-index: 2; /* should cover the black and red bars that are fixed-positioned */ } .intro * { font: inherit; margin: 0; padding: 0; } .intro h1 { font-size: 1em; font-weight: bolder; margin: 0; padding: 0; } .intro :link { color: blue; } .intro :visited { color: purple; } ``` -------------------------------- ### CSS Stacking and Float Divs Example Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/zindex/z-index8.html This CSS code defines styles for different div elements to demonstrate stacking contexts and float layouts. It includes styles for normal, absolutely positioned, and floated divs, influencing their rendering order and position on the page. No external dependencies are required. ```css div { font: 12px Arial; } span.bold { font-weight: bold; } #absdiv1 { opacity: 0.7; position: absolute; width: 150px; height: 200px; top: 10px; right: 140px; border: 1px solid #990000; background-color: #ffdddd; text-align: center; } #normdiv { height: 100px; border: 1px solid #999966; background-color: #ffffcc; margin: 0px 10px 0px 10px; text-align: left; } #flodiv1 { opacity: 0.7; margin: 0px 10px 0px 20px; float: left; width: 150px; height: 200px; border: 1px solid #009900; background-color: #ccffcc; text-align: center; } #flodiv2 { opacity: 0.7; margin: 0px 20px 0px 10px; float: right; width: 150px; height: 200px; border: 1px solid #009900; background-color: #ccffcc; text-align: center; } #absdiv2 { opacity: 0.7; position: absolute; width: 150px; height: 100px; top: 130px; left: 100px; border: 1px solid #990000; background-color: #ffdddd; text-align: center; } ``` -------------------------------- ### Handle Cross-Origin Images with html2canvas (CORS/Proxy) Source: https://context7.com/niklasvh/html2canvas/llms.txt This snippet demonstrates how to configure html2canvas to handle cross-origin images by either enabling CORS support (requires server configuration) or by specifying a proxy server. It includes examples for both methods and a mixed approach with error handling. The library needs to be included, and the server must be set up correctly for CORS. ```javascript html2canvas(document.body, { useCORS: true, allowTaint: false }).then(canvas => { document.body.appendChild(canvas); }); html2canvas(document.body, { proxy: 'https://my-server.com/html2canvas-proxy', imageTimeout: 10000 }).then(canvas => { document.body.appendChild(canvas); }).catch(err => { console.error('Proxy loading failed:', err); }); async function captureWithImages() { try { const canvas = await html2canvas(document.body, { useCORS: true, logging: false }); return canvas; } catch (error) { console.warn('CORS failed, trying with proxy'); return await html2canvas(document.body, { proxy: 'https://proxy.example.com/cors', allowTaint: false }); } } captureWithImages().then(canvas => { const dataUrl = canvas.toDataURL('image/png'); console.log('Screenshot captured:', dataUrl); }); ``` -------------------------------- ### Apply Gradient Background (CSS) Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/background/linear-gradient.html This CSS snippet defines a linear gradient background using the W3C standard and vendor prefixes. The gradient starts from the top and transitions through several shades of blue and grey. It includes color stops defined by percentages. ```css .linearGradient6 { /* FF 3.6+ */ background: -moz-linear-gradient(left, #cedbe9 0%, #aac5de 17%, #6199c7 50%, #3a84c3 51%, #419ad6, #26558b 100%); /* Chrome 10+, Safari 5.1+ */ background: -webkit-linear-gradient(left, #cedbe9 0%, #aac5de 17%, #6199c7 50%, #3a84c3 51%, #419ad6, #26558b 100%); /* Opera 11.10+ */ background: -o-linear-gradient(left, #cedbe9 0%, #aac5de 17%, #6199c7 50%, #3a84c3 51%, #419ad6, #26558b 100%); /* IE10+ */ background: -ms-linear-gradient(left, #cedbe9 0%, #aac5de 17%, #6199c7 50%, #3a84c3 51%, #419ad6, #26558b 100%); /* W3C */ background: linear-gradient(left, #cedbe9 0%, #aac5de 17%, #6199c7 50%, #3a84c3 51%, #419ad6, #26558b 100%); } ``` -------------------------------- ### Build Browser Bundle for html2canvas using npm Source: https://github.com/niklasvh/html2canvas/blob/master/README.md This command builds the browser-ready bundle for the html2canvas library using npm scripts. It compiles the source code into a distributable format for use in web browsers. ```bash npm run build ``` -------------------------------- ### Get Canvas as Base64 String Source: https://context7.com/niklasvh/html2canvas/llms.txt Asynchronously converts a given DOM element into a canvas, then extracts its content as a PNG image encoded in base64. It removes the data URI prefix, returning only the base64 string, suitable for embedding directly into `` tags. ```javascript async function getScreenshotBase64(element) { const canvas = await html2canvas(element); return canvas.toDataURL('image/png').split(',')[1]; // Remove data:image/png;base64, prefix } getScreenshotBase64(document.body).then(base64 => { console.log('Base64 length:', base64.length); // Use in img tag: }); ``` -------------------------------- ### CSS z-index for Division Element #5 Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/zindex/z-index10.html This snippet defines the CSS properties for 'Division Element #5', setting its position to relative and its z-index to 1. This is the lowest z-index among the examples, meaning it will be stacked below most other positioned elements. ```css #div5 { z-index: 1; margin-top: 15px; padding: 5px 10px; } ``` -------------------------------- ### Clone html2canvas Git Repository Source: https://github.com/niklasvh/html2canvas/blob/master/README.md This command clones the html2canvas Git repository from its remote URL. This is the first step to obtaining the library's source code for building or contributing. ```bash git clone git://github.com/niklasvh/html2canvas.git ``` -------------------------------- ### Render HTML Element to Canvas using html2canvas (JavaScript) Source: https://context7.com/niklasvh/html2canvas/llms.txt Demonstrates the core functionality of html2canvas to convert an HTML element into a canvas. It shows basic usage with the entire document body, rendering a specific element, and includes error handling. The function accepts a target element and returns a Promise that resolves with the generated canvas. Dependencies: html2canvas library. ```javascript import html2canvas from 'html2canvas'; // Basic usage - render entire document body html2canvas(document.body).then(function(canvas) { document.body.appendChild(canvas); }); // Render a specific element const element = document.querySelector('#my-element'); html2canvas(element).then(function(canvas) { // Convert canvas to image and download const link = document.createElement('a'); link.download = 'screenshot.png'; link.href = canvas.toDataURL(); link.click(); }); // With error handling html2canvas(document.getElementById('content')) .then(canvas => { console.log('Canvas generated successfully'); document.body.appendChild(canvas); }) .catch(error => { console.error('Failed to generate canvas:', error); }); ``` -------------------------------- ### Preload Content with html2canvas Source: https://github.com/niklasvh/html2canvas/wiki/Documentation Initiates the preloading process for html2canvas, gathering images and generating dynamic graphics. It accepts an element to render and an options object for configuration, including callbacks, logging, proxy settings, and timeouts. The function returns an object with helper methods. ```javascript html2canvas.Preload( element, options ); ``` -------------------------------- ### Apply Gradient Background (CSS) Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/background/linear-gradient.html This CSS snippet applies a linear gradient background from top to bottom. It includes vendor prefixes for compatibility and uses standard CSS syntax for modern browsers. The gradient transitions through multiple color stops, starting with a light color and ending with a dark one. ```css .linearGradient5 { /* FF 3.6+ */ background: -moz-linear-gradient(top, #f0b7a1 0%, #8c3310 50%, #752201 51%, #bf6e4e 100%); /* Chrome, Safari 4+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f0b7a1), color-stop(50%, #8c3310), color-stop(51%, #752201), color-stop(100%, #bf6e4e)); /* Chrome 10+, Safari 5.1+ */ background: -webkit-linear-gradient(top, #f0b7a1 0%, #8c3310 50%, #752201 51%, #bf6e4e 100%); /* Opera 11.10+ */ background: -o-linear-gradient(top, #f0b7a1 0%, #8c3310 50%, #752201 51%, #bf6e4e 100%); /* IE 10+ */ background: -ms-linear-gradient(top, #f0b7a1 0%, #8c3310 50%, #752201 51%, #bf6e4e 100%); /* W3C */ background: linear-gradient(top, #f0b7a1 0%, #8c3310 50%, #752201 51%, #bf6e4e 100%); } ``` -------------------------------- ### Export Canvas to PNG and Download Source: https://context7.com/niklasvh/html2canvas/llms.txt Converts the generated canvas to a PNG image and triggers a download. It demonstrates two methods: using `toDataURL` to create a data URI and `toBlob` for more efficient blob handling. Both methods create a link element to initiate the download. ```javascript // Export as PNG and download html2canvas(document.querySelector('#report')).then(canvas => { // Method 1: Using toDataURL const dataURL = canvas.toDataURL('image/png'); const link = document.createElement('a'); link.download = 'report.png'; link.href = dataURL; link.click(); // Method 2: Using toBlob (more efficient) canvas.toBlob(function(blob) { const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.download = 'report.png'; link.href = url; link.click(); URL.revokeObjectURL(url); }, 'image/png'); }); ``` -------------------------------- ### Draw Custom Shapes on Canvas using JavaScript Source: https://github.com/niklasvh/html2canvas/blob/master/examples/existing_canvas.html This snippet illustrates how to draw a custom graphic, specifically a smiley face, directly onto an HTML canvas element using the native Canvas API in JavaScript. It involves getting the 2D rendering context and using methods like beginPath, arc, and moveTo to define and draw the shape. This code does not rely on external libraries. ```javascript var canvas = document.querySelector("canvas"); var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle ctx.moveTo(110,75); ctx.arc(75,75,35,0,Math.PI,false); // Mouth (clockwise) ctx.moveTo(65,65); ctx.arc(60,65,5,0,Math.PI*2,true); // Left eye ctx.moveTo(95,65); ctx.arc(90,65,5,0,Math.PI*2,true); // Right eye ctx.stroke(); ``` -------------------------------- ### Create Content Dynamically with JavaScript Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/text/multiple.html Demonstrates how to create HTML content programmatically using JavaScript. This snippet focuses on generating elements and appending them to the document, a common task when building dynamic user interfaces. ```javascript console.log('Creating content through JavaScript'); ``` -------------------------------- ### Test Text Decorations with JavaScript and jQuery Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/text/multiple.html This snippet sets up a test environment by clearing the body and creating multiple divs with different font families and sizes. It then applies various text decorations (underline, overline, line-through) and colors to test their rendering. Dependencies include jQuery. ```javascript function setUp() { $('body').empty(); $.each(['arial','verdana','courier new'],function(i,e){ var div = $('
').css('font-family',e).appendTo('body'); for(var i=0;i<=5;i++){ $('
').text('Testing texts').css('margin-top',1).css('border','1px solid black').css('font-size',(16+i*6)).appendTo(div); } }); } $('.small').css('font-size','14px'); $('.medium').css('font-size','18px'); $('.large').css('font-size','24px'); div { text-decoration: underline overline line-through; text-decoration-color: red; } .lineheight { line-height: 40px; } h2 { clear:both; } ``` -------------------------------- ### JavaScript: Set up DOM for Text Decoration Tests Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/text/underline-lineheight.html This JavaScript function sets up the Document Object Model (DOM) by clearing the body and appending divs with different font families and sizes to test text decorations. It iterates through common font families and font sizes to prepare the testing environment. ```javascript function setUp() { $('body').empty(); $.each(['arial','verdana','tahoma','courier new'],function(i,e){ var div = $('
').css('font-family',e).appendTo('body'); for(var i=0;i<=10;i++){ $('
').text('Testing texts').css('margin-top',1).css('font-size',(16+i*6)).appendTo(div); } }); } ``` -------------------------------- ### Render HTML to Canvas with html2canvas (JavaScript) Source: https://github.com/niklasvh/html2canvas/blob/master/examples/demo2.html This snippet demonstrates how to use the html2canvas library to render the entire document body into a canvas element and append it to the DOM. It requires the html2canvas library to be included in the project. The output is a canvas element. ```javascript html2canvas(document.body).then(function(canvas) { document.body.appendChild(canvas); }); ``` -------------------------------- ### CSS for Picture Layout and Introduction Message Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/acid2.html Styles specific to the 'picture' element and its components, including margins, text alignment, font styles, and borders. It also styles the introduction message with positioning and z-index for layering. ```css #top { margin: 100em 3em 0; padding: 2em 0 0 .5em; text-align: left; font: 2em/24px sans-serif; color: navy; white-space: pre; } .picture { position: relative; border: 1em solid transparent; margin: 0 0 100em 3em; } .picture { background: red; } /* overriden by preferred stylesheet below */ ``` -------------------------------- ### Test Text Decoration with JavaScript Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/text/underline.html This JavaScript function sets up a test environment for text decorations. It dynamically creates HTML elements with different font families and sizes to verify text rendering. It does not have external dependencies beyond standard browser APIs. ```javascript function setUp() { var container = document.querySelector('#test'); container.innerHTML = ''; ['arial','verdana','courier new'].forEach(function(e) { var div = document.createElement('div'); div.style.fontFamily = e; container.appendChild(div); for(var i=1;i<=10;i*=2) { var text = document.createElement('div'); text.innerText = 'Testing texts'; text.style.marginTop = '1px'; text.style.fontSize = (16+i*6) + 'px'; div.appendChild(text); } }); } ``` -------------------------------- ### Create and Replace CSS Style Sheet - JavaScript Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/webcomponents/webcomponents.html This snippet demonstrates how to create a new CSSStyleSheet object and then replace its content synchronously using `replaceSync`. This is useful for dynamically applying styles within a web component or application. It does not have external dependencies. ```javascript const sheet = new CSSStyleSheet(); sheet.replaceSync('* { color: red !important; }') ``` -------------------------------- ### CSS for Width, Overflow, and Background Images Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/acid2.html Styles elements related to the 'forehead' section, controlling width, borders, and background properties. It includes a data URI for a 1x1 pixel PNG as a background image and demonstrates width inheritance with child elements. ```css .forehead { margin: 4em; width: 8em; border-left: solid black 1em; border-right: solid black 1em; background: red url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mP4%2F58BAAT%2FAf9jgNErAAAAAElFTkSuQmCC) fixed 1px 0; /* that's a 1x1 yellow pixel PNG */ } .forehead * { width: 12em; line-height: 1em; } ``` -------------------------------- ### Render HTML on Existing Canvas with html2canvas Source: https://context7.com/niklasvh/html2canvas/llms.txt This snippet shows how to render HTML content onto a pre-existing canvas element instead of creating a new one. This is useful for compositing or progressive rendering scenarios. It requires a canvas element and the html2canvas library. ```javascript const existingCanvas = document.querySelector('canvas'); const ctx = existingCanvas.getContext('2d'); ctx.beginPath(); ctx.arc(75, 75, 50, 0, Math.PI * 2, true); ctx.stroke(); html2canvas(document.querySelector('#content'), { canvas: existingCanvas, scale: 1 }).then(function(canvas) { console.log('HTML rendered on existing canvas'); }); const thumbnailCanvas = document.createElement('canvas'); thumbnailCanvas.width = 400; thumbnailCanvas.height = 300; const thumbCtx = thumbnailCanvas.getContext('2d'); thumbCtx.strokeStyle = '#333'; thumbCtx.lineWidth = 4; thumbCtx.strokeRect(0, 0, 400, 300); html2canvas(document.querySelector('#article'), { canvas: thumbnailCanvas, width: 392, height: 292, x: 4, y: 4 }).then(() => { document.body.appendChild(thumbnailCanvas); }); ``` -------------------------------- ### CSS for Nose Element with Auto Margins and Sizing Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/acid2.html Styles the 'nose' element, testing float positioning, negative margins, borders, and complex height calculations using percentages and keywords. It demonstrates how percentages for height are treated as 'auto' in certain contexts. ```css .nose { float: left; margin: -2em 2em -1em; border: solid 1em black; border-top: 0; min-height: 80%; height: 60%; max-height: 3em; /* percentages become auto (see 10.5 and 10.7) and intrins ``` -------------------------------- ### CSS for Class Selectors and Specificity Tests Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/acid2.html Tests the specificity and matching behavior of class selectors. Includes rules that should and should not match based on combinations of classes and element types, affecting background colors. ```css .two.error.two { background: maroon; } /* shouldn't match */ .forehead.error.forehead { background: red; } /* shouldn't match */ [class=second two] { background: red; } /* this should be ignored (invalid selector -- grammar says it only accepts IDENTs or STRINGs) */ ``` -------------------------------- ### CSS for Attribute Selectors and Floats Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/acid2.html Applies styling using attribute selectors, including class substring matching and specific class combinations. It also utilizes float positioning and sets dimensions and background colors for these elements. ```css [class~=one].first.one { position: absolute; top: 0; margin: 36px 0 0 60px; padding: 0; border: black 2em; border-style: none solid; /* shrink wraps around float */ } [class~=one][class~=first] [class=second\ two][class="second two"] { float: right; width: 48px; height: 12px; background: yellow; margin: 0; padding: 0; } /* only content of abs pos block */ ``` -------------------------------- ### Create and Style Div Elements with JavaScript (jQuery) Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/text/linethrough.html This JavaScript code snippet, using jQuery, dynamically creates div elements, appends them to the body, and applies various CSS properties such as font-family, font-size, and text-decoration. It's designed for testing text rendering under different conditions. ```javascript function setUp() { $('body').empty(); $.each(['arial','verdana','courier new'],function(i,e){ var div = $('
').css('font-family',e).appendTo('body'); for(var i=0;i<=5;i++){ $('
').text('Testing texts').css('margin-top',1).css('border','1px solid black').css('font-size',(16+i*6)).appendTo(div); } }); } ``` -------------------------------- ### Draw HTML onto Existing Canvas with html2canvas Source: https://github.com/niklasvh/html2canvas/blob/master/examples/existing_canvas.html This snippet demonstrates how to use the html2canvas library to render specific HTML content onto a canvas element that already exists on the page. It requires the html2canvas library to be included and targets an element with the ID 'content' to be rendered onto a selected canvas. The output is the modified canvas. ```javascript var canvas = document.querySelector("canvas"); document.querySelector("button").addEventListener("click", function() { html2canvas(document.querySelector("#content"), { canvas: canvas, scale: 1 }).then(function(canvas) { console.log('Drew on the existing canvas'); }); }, false); ``` -------------------------------- ### CSS Background Size and Position Styles Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/background/size.html These CSS rules define background image properties, including URL, position, and size for different HTML elements. They are used to test how html2canvas handles various background configurations. ```css .horizontal div, .vertical div { display: block; background: url("../../assets/image.jpg") center center; } .sliver div { background: url("../../assets/bg-sliver.png") center center; background-size: 650px auto; } .vertical { float: right; } .horizontal { float: left; } .horizontal div { width: 400px; height: 100px; } .vertical div { width: 200px; height: 200px; } .container { float: left; border: 1px solid black; width: 150px; height: 200px; background-image: url(../../assets/image.jpg); background-size: 34px; background-repeat: no-repeat; background-position: center; } ``` -------------------------------- ### CSS for Eyes Elements with Paint Order and Backgrounds Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/acid2.html Styles the 'eyes' elements, testing absolute positioning, paint order, and background properties. It uses data URIs for background images and demonstrates how inline, floating, and block elements interact with background rendering. ```css .eyes { position: absolute; top: 5em; left: 3em; margin: 0; padding: 0; background: red; } #eyes-a { height: 0; line-height: 2em; text-align: right; } /* contents should paint top-most because they're inline */ #eyes-a object { display: inline; vertical-align: bottom; } #eyes-a object[type] { width: 7.5em; height: 2.5em; } /* should have no effect since that object should fallback to being inline (height/width don't apply to inlines) */ #eyes-a object object object { border-right: solid 1em black; padding: 0 12px 0 11px; background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAABnRSTlMAAAAAAABupgeRAAAABmJLR0QA%2FwD%2FAP%2BgvaeTAAAAEUlEQVR42mP4%2F58BCv7%2FZwAAHfAD%2FabwPj4AAAAASUVORK5CYII%3D) fixed 1px 0; } #eyes-b { float: left; width: 10em; height: 2em; background: fixed url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAABnRSTlMAAAAAAABupgeRAAAABmJLR0QA%2FwD%2FAP%2BgvaeTAAAAEUlEQVR42mP4%2F58BCv7%2FZwAAHfAD%2FabwPj4AAAAASUVORK5CYII%3D); border-left: solid 1em black; border-right: solid 1em red; } /* should paint in the middle layer because it is a float */ #eyes-c { display: block; background: red; border-left: 2em solid yellow; width: 10em; height: 2em; } /* should paint bottom most because it is a block */ ``` -------------------------------- ### CSS Box Shadow Variations for html2canvas Testing Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/background/box-shadow.html This snippet demonstrates various CSS box-shadow properties, including single, multiple, inset, and colored shadows. It's designed to test the html2canvas library's ability to accurately render these effects. Dependencies include a basic HTML structure with a .boxshadow class. ```css .boxshadow { margin: 10px; display: inline-block; min-height: 50px; border-radius: 10px; } body { max-width: 800px; } /* Single and multiple shadows */ 0 0 0 0.5em; 0 0 1em; 1em 0.5em; 1em 0.5em 1em; 0 2em 1em -0.7em; /* Colored shadows */ 0.3em 0.3em lightgreen; 0.3em 0.3em 0 0.6em lightgreen; 0 2em 0 -0.9em lightgreen; 2em 1.5em 0 -0.7em lightgreen; 9em 1.2em 0 -0.6em lightgreen; -27.3em 0 lightgreen; 0 2em 0 -1em lightgreen; 0 0 1em maroon; 0 0 1em 0.5em maroon; 0 0 1em 1em maroon; -0.4em -0.4em 1em olive; 0.4em 0.4em 1em olive; 0.4em 0.4em 1em -0.2em olive; 0.4em 0.4em 1em 0.4em olive; 0 1.5em 0.5em -1em olive; /* Inset shadows */ inset 0.2em 0.4em red, inset -1em -0.7em red; inset 11em 0 red; inset -1em 0 red; inset 13em 0 3em -3em orange,inset -3em 0 3em -3em blue; inset 11em 0 2em orange; inset 0 0.3em red; inset 0 -1.1em red; inset 1em 0 1em -1em blue; inset 0 0 0.5em blue; inset 0 0 2em blue; inset 0 2em 3em -1em green; inset 0 2em 3em -2em green; inset 0 2em 3em -3em green; inset 0 0 1em khaki; inset 0 0 1em khaki, inset 0 0 1em khaki, inset 0 0 1em khaki, inset 0 0 1em khaki; inset 0 0 0.5em 0.5em khaki; /* seamless if */ inset 0 0 0.5em 0.5em khaki; inset 0 0 2em 2em khaki; 0 0 0.5em 0.5em teal; inset 0 0 0.5em 0.5em indigo, 0 0 0.5em 0.5em indigo; inset 0 0 1em black, inset 0 0 1em black, inset 0 0 1em black, inset 0 0 1em black; inset 0 0 0.7em 0.5em black; /* should be very similar to above */ inset 0 2em 3em -1.5em green, inset 0 -2em 3em -2em blue; inset 1em 1em 2em -1em blue; inset 1em 1em 2em -1em blue, inset -1em -1em 2em -1em red; inset 0 2em 3em -2em white, inset 0 -2em 3em -2.5em black; inset 1em 1em 1em -1em white, inset -1em -1em 1em -1em black; inset -1em -1em 1em -1em black, inset 1em 1em 1em -1em white; inset -0.3em -0.3em 0.6em rgba(0,0,0,0.5), inset 0.3em 0.3em 0.6em rgba(256,256,256,0.7); inset 0.3em 0.3em 0.6em rgba(256,256,256,0.5), inset -0.3em -0.3em 0.6em rgba(0,0,0,0.5); 0.2em 0.2em 0.7em black, inset 0 0 0.7em red; ``` -------------------------------- ### Apply Gradient Background (CSS) Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/background/linear-gradient.html This snippet demonstrates applying a linear gradient background with vendor prefixes and standard CSS syntax. The gradient transitions from red to blue, with specific color stops defined. Note the commented-out older webkit-gradient syntax. ```css .linearGradient { /*background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgb(255, 0, 0)), to(rgb(0, 0, 255)));*/ background: -webkit-linear-gradient(top left, #f00, #00f, #BADA55, rgba(0, 0, 255,0.5)); background: -moz-linear-gradient(top left, #f00, #00f, #BADA55, rgba(0, 0, 255,0.5)); } ``` -------------------------------- ### CSS Radial Gradient (Basic) Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/background/radial-gradient.html This snippet defines a basic radial gradient background using standard CSS and vendor prefixes for broader browser compatibility. It sets up a radial gradient with color stops. ```css /* FF 3.6+ */ background: -moz-radial-gradient(center, ellipse cover, #959595 0%, #0d0d0d 48%, #2f7bd8 50%, #0a0a0a 64%, #4e4e4e 80%, #383838 87%, #1b1b1b 100%); /* Chrome, Safari 4+ */ background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%,#959595), color-stop(48%,#0d0d0d), color-stop(50%,#2f7bd8), color-stop(64%,#0a0a0a), color-stop(80%,#4e4e4e), color-stop(87%,#383838), color-stop(100%,#1b1b1b)); /* Chrome 10+, Safari 5.1+ */ background: -webkit-radial-gradient(center, ellipse cover, #959595 0%, #0d0d0d 48%,#2f7bd8 50%,#0a0a0a 64%,#4e4e4e 80%,#383838 87%,#1b1b1b 100%); /* Opera 12+ */ background: -o-radial-gradient(center, ellipse cover, #959595 0%, #0d0d0d 48%,#2f7bd8 50%,#0a0a0a 64%,#4e4e4e 80%,#383838 87%,#1b1b1b 100%); /* IE 10+ */ background: -ms-radial-gradient(center, ellipse cover, #959595 0%,#0d0d0d 48%,#2f7bd8 50%,#0a0a0a 64%,#4e4e4e 80%,#383838 87%,#1b1b1b 100%); /* W3C */ background: radial-gradient(center, ellipse cover, #959595 0%,#0d0d0d 48%,#2f7bd8 50%,#0a0a0a 64%,#4e4e4e 80%,#383838 87%,#1b1b1b 100%); ``` -------------------------------- ### CSS for Hidden Elements and Combinator Selectors Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/acid2.html Styles elements intended to be hidden or those affected by combinator selectors. It includes rules for 'p.bad' and 'p + p' to test border and background properties, as well as 'p + table + p' to test margin-top behavior. ```css .picture p.bad { border-bottom: red solid; /* shouldn't matter, because the "p + table + p" rule below should match it too, thus hiding it */ } .picture p + p { background: maroon; z-index: 1; } /* shouldn't match anything */ .picture p + table + p { margin-top: 3em; /* should end up under the absolutely positioned table below, and thus not be visible */ } ``` -------------------------------- ### Export Canvas to JPEG and Upload Source: https://context7.com/niklasvh/html2canvas/llms.txt Converts the canvas to a JPEG image with specified quality and prepares it for upload to a server using `FormData` and the `fetch` API. This is useful for sending screenshots to a backend service. ```javascript // Method 3: JPEG with quality control canvas.toBlob(function(blob) { // Upload to server const formData = new FormData(); formData.append('screenshot', blob, 'screenshot.jpg'); fetch('/api/screenshots', { method: 'POST', body: formData }).then(response => response.json()) .then(data => console.log('Uploaded:', data.url)); }, 'image/jpeg', 0.85); // 85% quality ``` -------------------------------- ### Insert CSS Rule Dynamically using JavaScript Source: https://github.com/niklasvh/html2canvas/blob/master/tests/reftests/dynamicstyle.html Demonstrates how to dynamically insert a CSS rule into a stylesheet using JavaScript. This method is useful for applying styles on the fly without reloading the page. It targets a specific stylesheet by its ID and appends a new rule to its end. ```javascript document.querySelector('#style').sheet.insertRule( '.div2 { background: darkgreen; color:white; }', document.querySelector('#style').sheet.cssRules.length ); ``` -------------------------------- ### Capture Scrolled Content with html2canvas Viewport and Scrolling Options Source: https://context7.com/niklasvh/html2canvas/llms.txt Capture content that is off-screen or within scrollable containers by controlling the viewport dimensions and scroll position using html2canvas options like 'scrollX', 'scrollY', 'windowWidth', and 'windowHeight'. Dependencies: html2canvas. ```javascript // Capture specific scroll position html2canvas(document.querySelector('#scrollable-content'), { scrollX: 0, scrollY: 500, // Start capture 500px down windowWidth: 1920, windowHeight: 1080 }).then(canvas => { document.body.appendChild(canvas); }); // Capture element with fixed positioning const fixedElement = document.querySelector('.fixed-header'); html2canvas(fixedElement, { scrollX: window.pageXOffset, scrollY: window.pageYOffset, x: 0, y: 0 }).then(canvas => { console.log('Fixed element captured'); }); // Capture full page by scrolling async function captureFullPage() { const scrollHeight = document.documentElement.scrollHeight; const viewportHeight = window.innerHeight; const canvases = []; for (let y = 0; y < scrollHeight; y += viewportHeight) { const canvas = await html2canvas(document.body, { scrollY: y, windowHeight: viewportHeight, height: Math.min(viewportHeight, scrollHeight - y) }); canvases.push(canvas); } // Combine all canvases vertically const fullCanvas = document.createElement('canvas'); fullCanvas.width = canvases[0].width; fullCanvas.height = scrollHeight; const ctx = fullCanvas.getContext('2d'); let offsetY = 0; canvases.forEach(canvas => { ctx.drawImage(canvas, 0, offsetY); offsetY += canvas.height; }); return fullCanvas; } captureFullPage().then(canvas => { console.log('Full page captured:', canvas.height); }); ```