### Complete Example with Error Handling Source: https://context7.com/cburgmer/rasterizehtml.js/llms.txt This comprehensive example demonstrates combining major features with error handling and resource failure reporting. It shows how to render HTML to a canvas, log success messages, check for partially loaded resources, and handle various rendering errors. ```javascript var canvas = document.getElementById("canvas"); var html = "\n \n \n \n \n \n \n

Report Title

\n

Hover text

\n \"Logo"\n \n \n"; var options = { width: 800, height: 600, baseUrl: window.location.href, hover: ".highlight", cache: 'repeated', zoom: window.devicePixelRatio || 1 }; rasterizeHTML.drawHTML(html, canvas, options) .then(function(result) { console.log("Render complete"); console.log("Output image size:", result.image.width, "x", result.image.height); // Check for partially loaded resources if (result.errors.length > 0) { console.warn("Some resources failed to load:"); result.errors.forEach(function(err) { console.warn(" - " + err.resourceType + ": " + err.url); }); } // Access the SVG representation console.log("SVG:", result.svg); }) .catch(function(error) { switch(error.message) { case "Unable to load page": console.error("Page could not be loaded (CORS issue?)"); break; case "Invalid source": console.error("HTML could not be parsed as valid XHTML"); break; case "Error rendering page": console.error("General rendering failure"); break; default: console.error("Unknown error:", error.message); } if (error.originalError) { console.error("Original error:", error.originalError); } }); ``` -------------------------------- ### Install rasterizeHTML via NPM Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/README.md Use this command to install the library as a dependency in your project. ```bash $ npm install rasterizehtml ``` -------------------------------- ### Get Image for URL Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/diffHelperPage.html Loads an image from a given URL and invokes a success or error callback. Ensure the URL is accessible. ```javascript var getImageForUrl = function ( url, successCallback, errorCallback, ) { var image = new window.Image(); image.onload = function () { successCallback(image); }; if (errorCallback) { image.onerror = errorCallback; } image.src = url; }; ``` -------------------------------- ### Style Element with Custom Webfont Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/fixtures/testFragment.html Apply a custom webfont defined with @font-face to an element. This example sets the font family, size, line height, and color. ```css .webfont { font-family: 'RaphaelIcons'; font-size: 100px; line-height: 100px; color: black; } ``` -------------------------------- ### Handle rendering promise Source: https://github.com/cburgmer/rasterizehtml.js/wiki/API Demonstrates the promise-based pattern for handling successful renders or errors. ```javascript rasterizeHTML.drawURL(url, canvas, options) .then(function success(renderResult) { ... }, function error(e) { ... }); ``` -------------------------------- ### Initialize and Render HTML to Canvas Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/examples/retina.html This script initializes the rasterizeHTML.js library to draw HTML content onto a canvas element. It includes logic for retina display scaling and an event listener for real-time updates. ```javascript var input = document.getElementById("input"), canvas = document.getElementById("canvas"), template = document.getElementById("template"), oldText = input.value; var backingScale = function () { if (window.devicePixelRatio && window.devicePixelRatio > 1) { return window.devicePixelRatio; } return 1; }; var parsePixelValue = function (value) { return parseInt(value, 10); }; var scaleCanvasForRetina = function (canvas) { var scaleFactor = backingScale(), canvasStyle = window.getComputedStyle(canvas); canvas.width = parsePixelValue(canvasStyle.width) * scaleFactor; canvas.height = parsePixelValue(canvasStyle.height) * scaleFactor; }; var drawHTML = function () { var scaleFactor = backingScale(); rasterizeHTML.drawHTML(input.value, canvas, { zoom: scaleFactor }); }; scaleCanvasForRetina(canvas); input.onkeyup = function () { if (input.value !== oldText) { oldText = input.value; canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height); drawHTML(); } }; if (!input.value) { input.value = template.innerHTML.replace(/^ {8}/gm, "").replace(/^\\n/g, "").replace(/\\n +$/g, "\\n"); } drawHTML(); ``` -------------------------------- ### Configure Retina/HiDPI Display Support Source: https://context7.com/cburgmer/rasterizehtml.js/llms.txt Scale the canvas dimensions and apply the zoom option to ensure sharp rendering on high-resolution displays. ```javascript var canvas = document.getElementById("canvas"); // Get device pixel ratio var scaleFactor = window.devicePixelRatio || 1; // Scale canvas dimensions for retina var style = window.getComputedStyle(canvas); canvas.width = parseInt(style.width) * scaleFactor; canvas.height = parseInt(style.height) * scaleFactor; // Render with zoom to match scale var html = '
Sharp text on retina
'; rasterizeHTML.drawHTML(html, canvas, { zoom: scaleFactor }).then(function(result) { console.log("Rendered at " + scaleFactor + "x resolution"); }); ``` -------------------------------- ### Render HTML Document to Canvas Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/manualIntegrationTest.html Uses a test helper to read an HTML document fixture and render it onto a specified canvas element. ```javascript testHelper .readHTMLDocumentFixture("test.html") .then(function (doc) { rasterizeHTML.drawDocument(doc, documentTestCanvas, { baseUrl: "fixtures/", cache: false, active: ".bgimage", hover: ".webfont", clip: "body", }); }); ``` -------------------------------- ### Load content via AJAX Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/fixtures/ajax.html Uses XMLHttpRequest to fetch content from a file and inject it into the DOM. Ensure the target file exists and is accessible via the same origin policy. ```javascript (function () { var xhr = new window.XMLHttpRequest(); xhr.addEventListener("load", function () { document.querySelector('div').textContent = xhr.responseText; }, false); xhr.open('GET', 'ajaxContent.txt', true); xhr.send(null); }()); ``` -------------------------------- ### Apply Content Security Policy Nonce Source: https://context7.com/cburgmer/rasterizehtml.js/llms.txt Pass a nonce value to the rendering options to support environments with strict Content Security Policies. ```javascript var canvas = document.getElementById("canvas"); var html = '

Styled content

'; // Get nonce from page's CSP meta tag or header var nonce = document.querySelector('script[nonce]')?.nonce; rasterizeHTML.drawHTML(html, canvas, { nonce: nonce }).then(function(result) { console.log("Rendered with CSP nonce"); }); ``` -------------------------------- ### Render HTML with CSS Pseudo-classes Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/examples/pseudoClasses.html Uses rasterizeHTML.drawHTML to apply hover, active, focus, and target states to rendered HTML on a canvas. Requires an input element for HTML and selector inputs for state management. ```css canvas, textarea { display: block; border: 1px solid gray; margin: 3px 0; } ``` ```html A link

Caption

A div
``` ```javascript var oldText = input.value; var render = function () { var html = input.value, hover = hoverSelector.value, active = activeSelector.value, focus = focusSelector.value, target = targetSelector.value; canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height); rasterizeHTML.drawHTML(input.value, canvas, { hover: hover, active: active, focus: focus, target: target }); }; input.onkeyup = function () { if (input.value !== oldText) { oldText = input.value; render(); } }; hoverSelector.onchange = render; activeSelector.onchange = render; focusSelector.onchange = render; targetSelector.onchange = render; if (!input.value) { input.value = template.innerHTML.replace(/^ {8}/gm, "").replace(/^\n/g, "").replace(/\n +$/g, "\n"); } render(); ``` -------------------------------- ### Run Performance Test with rasterizeHTML.js Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/performance.html Initiates a performance test by calling the run function with a specified number of rendering runs and the target URL. This function logs the test progress and results to a console element. ```javascript var url = "fixtures/test.html", cache = {}; var renderPageMultipleTimes = function (count, tick) { var canvas = document.getElementById("canvas"); if (count === 0) { return; } return rasterizeHTML .drawURL(url, canvas, { active: ".bgimage", hover: ".webfont", clip: "body", cacheBucket: cache, }) .then(function (result) { count -= 1; tick(count, result.errors); return renderPageMultipleTimes(count, tick); }); }; var log = function (msg) { var pre = document.getElementById("console"); pre.textContent += msg; }; var run = function (runs, url) { var startTime = Date.now(), firstStepEndTime; log( "Running performance test against " + url + " with " + runs + " runs\n", ); renderPageMultipleTimes(runs, function (stepsLeft, errors) { if (stepsLeft === runs - 1) { firstStepEndTime = Date.now(); errors.forEach(function (error) { console.log(error); }); } log("."); if (stepsLeft === 0) { log("\n"); } }).then(function () { var endTime = Date.now(); log("Results:\n"); log( Math.floor((endTime - startTime) / runs) + " milliseconds on average\n", ); log( Math.floor(firstStepEndTime - startTime) + " milliseconds for first call\n", ); log( Math.floor((endTime - firstStepEndTime) / (runs - 1)) + " milliseconds on avarage for remaining\n", ); }); }; run(10, url); ``` -------------------------------- ### Render URL to Canvas or Image Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/manualIntegrationTest.html Renders content directly from a URL to a canvas or creates an image element from the result. ```javascript rasterizeHTML.drawURL( "fixtures/testScaled50PercentWithJs.html", urlTestScaled50PercentWithJsCanvas, { cache: false, executeJs: true, executeJsTimeout: 100, zoom: 2, active: ".bgimage", hover: ".webfont", focus: "img", clip: "body", }, ); ``` ```javascript rasterizeHTML .drawURL("fixtures/testScaled50PercentWithJs.html", { cache: false, executeJs: true, executeJsTimeout: 100, zoom: 2, width: 200, height: 100, active: ".bgimage", hover: ".webfont", focus: "img", clip: "body", }) .then(function (result) { urlTestScaled50PercentWithJsImageContainer.appendChild( result.image, ); }); ``` -------------------------------- ### Compare Image URLs with Threshold Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/diffHelperPage.html Compares two images from URLs for equality within a given threshold, rendering differences if found. Returns a Promise that resolves to a boolean indicating equality. ```javascript var isEqual = function (imageUrl1, imageUrl2, threshold) { return new Promise(function (fulfill) { getImageForUrl(imageUrl1, function (image1) { getImageForUrl(imageUrl2, function (image2) { var equal = diffHelper.imageEquals( image1, image2, threshold, ); renderDiff(image1, image2); fulfill(equal); }); }); }); }; ``` -------------------------------- ### Simulate CSS Pseudo-Class States Source: https://context7.com/cburgmer/rasterizehtml.js/llms.txt Use the options object to trigger specific CSS pseudo-class states on elements during rendering. ```javascript var canvas = document.getElementById("canvas"); var html = ` Hover me
Target section
`; // Render with simulated hover state rasterizeHTML.drawHTML(html, canvas, { hover: ".link" // CSS selector for hover state }); // Render with multiple pseudo-class states rasterizeHTML.drawHTML(html, canvas, { hover: ".link", active: ".link", focus: ".link", target: "#section" }); ``` -------------------------------- ### Render HTML String to Canvas Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/manualIntegrationTest.html Renders an HTML string fixture to a canvas, supporting configuration for base URLs, caching, and CSS pseudo-class states. ```javascript testHelper.readHTMLFixture("test.html").then(function (html) { rasterizeHTML.drawHTML(html, htmlTestCanvas, { baseUrl: "fixtures/", cache: false, active: ".bgimage", hover: ".webfont", clip: "body", }); }); ``` ```javascript testHelper .readHTMLFixture("testScaled50PercentWithJs.html") .then(function (html) { rasterizeHTML.drawHTML( html, htmlTestScaled50PercentWithJsCanvas, { baseUrl: "fixtures/", cache: false, executeJs: true, executeJsTimeout: 100, zoom: 2, active: ".bgimage", hover: ".webfont", focus: "img", clip: "body", }, ); }); ``` -------------------------------- ### Import TypeScript Definitions Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/README.md Use this import statement to include type definitions in a TypeScript project. ```ts import * as rasterizeHTML from 'rasterizehtml'; ``` -------------------------------- ### Draw URL to canvas Source: https://github.com/cburgmer/rasterizehtml.js/wiki/API Renders the content of a URL onto the specified canvas. ```javascript rasterizeHTML.drawURL( url [, canvas] [, options] ) ``` -------------------------------- ### Manage Resource Caching Source: https://context7.com/cburgmer/rasterizehtml.js/llms.txt Control how external resources are cached during rendering to optimize performance or development workflows. ```javascript var canvas = document.getElementById("canvas"); var html = ''; // Disable all caching (adds timestamp to requests) rasterizeHTML.drawHTML(html, canvas, { cache: 'none' }); // Cache repeated requests only (first request uncached) rasterizeHTML.drawHTML(html, canvas, { cache: 'repeated' }); // Use in-memory cache bucket for multiple renders var cacheBucket = {}; rasterizeHTML.drawHTML(html, canvas, { cache: 'all', cacheBucket: cacheBucket }); // Subsequent renders reuse cached resources rasterizeHTML.drawHTML(html, canvas, { cache: 'all', cacheBucket: cacheBucket // Same bucket }); ``` -------------------------------- ### CSS Test Styles for rasterizeHTML.js Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/fixtures/testScaled50PercentWithJs.html Styles used to verify rendering behavior for hover/active states, media queries, and layout positioning. ```css .teST { margin: 0; padding: 0; vertical-align: top; position: relative; /* Reproduce https://github.com/cburgmer/rasterizeHTML.js/pull/109 */ } div.teST { float: left; width: 50px; height: 50px; } /* Catch https://bugzilla.mozilla.org/show_bug.cgi?id=986403 */ @media (max-width: 200px) { .webfont { font-size: 5rem; line-height: 5rem; } } HTmL { padding: 20px 17px 4px 12px; background-color: orange; font-size: 10px; /* Force rendering on same line, esp. for Firefox on Linux */ width: 100px; overflow: hidden; } img { opacity: 0.1; } img:focus { opacity: 1; } html { overflow-y: scroll; } ``` -------------------------------- ### Render URL to Canvas with rasterizeHTML.js Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/integrationTestPage.html Use this snippet to draw a specified URL onto a canvas element. It includes configuration for JS execution, resource caching, and CSS pseudo-class states. ```javascript var canvas = document.getElementById("canvas"); rasterizeHTML .drawURL("fixtures/testScaled50PercentWithJs.html", canvas, { cache: false, executeJs: true, executeJsTimeout: 100, zoom: 2, active: ".bgimage", hover: ".webfont", focus: "img", clip: "body", }) .then( function (result) { if (result.errors.length > 0) { console.log( "Could not load the following resources: ", errors .map(function (e) { return e.msg; }) .join(", "), ); } }, function (err) { console.error(err); }, ); ``` -------------------------------- ### Create Canvas from Image Data Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/diffHelperPage.html Converts image data into an HTML canvas element. Requires a 2D rendering context. ```javascript var canvasForImageCanvas = function (imageData) { var canvas = document.createElement("canvas"), context; canvas.height = imageData.height; canvas.width = imageData.width; context = canvas.getContext("2d"); context.putImageData(imageData, 0, 0); return canvas; }; ``` -------------------------------- ### Failed Resource Object Structure Source: https://github.com/cburgmer/rasterizehtml.js/wiki/API This object represents a single failed resource. It includes the type of resource, the URL that failed to load, and a human-readable error message. ```javascript ```{ resourceType: "TYPE_OF_RESOURCE", url: "THE_FAILED_URL", msg: "A_HUMAN_READABLE_MSG" }``` ``` -------------------------------- ### Draw HTML to Canvas with rasterizeHTML.js Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/examples/index.html This snippet shows how to use `rasterizeHTML.drawHTML` to render an HTML string onto a canvas element. It includes basic error handling and logging of the result. Ensure the canvas element is available in the DOM. ```javascript var input = document.getElementById("input"), canvas = document.getElementById("canvas"), template = document.getElementById("template"), oldText = input.value; var draw = function () { rasterizeHTML.drawHTML(input.value, canvas).then(function (result) { console.log(result); }, function (e) { console.log('An error occured:', e); }); }; input.onkeyup = function () { if (input.value !== oldText) { oldText = input.value; canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height); draw(); } }; if (!input.value) { input.value = template.innerHTML.replace(/^ {8}/gm, "").replace(/^\\n/g, "").replace(/\\n +$/g, "\\n"); } draw(); ``` -------------------------------- ### Render HTML String to Canvas with rasterizeHTML.js Source: https://context7.com/cburgmer/rasterizehtml.js/llms.txt Use drawHTML to render an HTML string to a canvas element. It returns a Promise that resolves with rendering results or rejects on error. Options can customize viewport and resource loading. ```javascript var canvas = document.getElementById("canvas"); var html = '
Hello World
'; rasterizeHTML.drawHTML(html, canvas) .then(function(result) { console.log("Rendered successfully!"); console.log("Image dimensions:", result.image.width, "x", result.image.height); console.log("Failed resources:", result.errors); }) .catch(function(error) { console.error("Rendering failed:", error.message); }); ``` ```javascript rasterizeHTML.drawHTML(html).then(function(result) { var ctx = canvas.getContext('2d'); ctx.drawImage(result.image, 10, 25); // Position at x:10, y:25 }); ``` ```javascript rasterizeHTML.drawHTML(html, canvas, { width: 800, height: 600, baseUrl: 'https://example.com/assets/', cache: 'none' // Disable caching }).then(function(result) { console.log("Rendered with custom viewport"); }); ``` -------------------------------- ### drawURL - Render Page from URL to Canvas Source: https://context7.com/cburgmer/rasterizehtml.js/llms.txt Loads an HTML page from a URL and renders it to the canvas. The page must be from the same origin or have CORS enabled. Useful for rendering existing HTML pages or templates. ```APIDOC ## drawURL - Render Page from URL to Canvas ### Description Loads an HTML page from a URL and renders it to the canvas. The page must be from the same origin or have CORS enabled. Useful for rendering existing HTML pages or templates. ### Method `rasterizeHTML.drawURL(url, canvas, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (string) - Required - The URL of the HTML page to render. - **canvas** (HTMLCanvasElement) - Optional - The canvas element to draw on. If not provided, an image object is returned. - **options** (object) - Optional - Configuration options for rendering. - **executeJs** (boolean) - Whether to execute JavaScript within the page. - **executeJsTimeout** (number) - Timeout in milliseconds for JavaScript execution. - **width** (number) - The width of the rendering viewport. - **height** (number) - The height of the rendering viewport. ### Request Example ```javascript var canvas = document.getElementById("canvas"); // Basic URL rendering rasterizeHTML.drawURL("template.html", canvas) .then(function(result) { console.log("Page rendered successfully"); }) .catch(function(error) { if (error.message === "Unable to load page") { console.error("Could not load the URL - check same-origin policy"); } }); // With JavaScript execution enabled rasterizeHTML.drawURL("interactive-page.html", canvas, { executeJs: true, executeJsTimeout: 2000, width: 1024, height: 768 }).then(function(result) { console.log("Page with JS rendered"); }); // Handling failed resources rasterizeHTML.drawURL("page-with-images.html", canvas) .then(function(result) { result.errors.forEach(function(err) { console.warn("Failed to load " + err.resourceType + ": " + err.url); }); }); ``` ### Response #### Success Response (Promise resolves with an object) - **image** (HTMLImageElement or HTMLCanvasElement) - The rendered image or canvas. - **svg** (string) - The SVG representation of the rendered content. - **errors** (array) - An array of objects detailing any resource loading errors. #### Response Example ```json { "image": "", "svg": "...", "errors": [ { "resourceType": "image", "url": "https://example.com/image.png" } ] } ``` ``` -------------------------------- ### Draw HTML string to canvas Source: https://github.com/cburgmer/rasterizehtml.js/wiki/API Renders a raw HTML string onto the specified canvas. ```javascript rasterizeHTML.drawHTML( html [, canvas] [, options] ) ``` -------------------------------- ### drawHTML - Render HTML String to Canvas Source: https://context7.com/cburgmer/rasterizehtml.js/llms.txt Renders an HTML string directly to a canvas element. This is the most common method for rendering dynamic HTML content. The method returns a Promise that resolves with the rendered image, SVG representation, and any resource loading errors. ```APIDOC ## drawHTML - Render HTML String to Canvas ### Description Renders an HTML string directly to a canvas element. This is the most common method for rendering dynamic HTML content. The method returns a Promise that resolves with the rendered image, SVG representation, and any resource loading errors. ### Method `rasterizeHTML.drawHTML(html, canvas, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **html** (string) - Required - The HTML string to render. - **canvas** (HTMLCanvasElement) - Optional - The canvas element to draw on. If not provided, an image object is returned. - **options** (object) - Optional - Configuration options for rendering. - **width** (number) - The width of the rendering viewport. - **height** (number) - The height of the rendering viewport. - **baseUrl** (string) - The base URL for resolving relative resources. - **cache** (string) - Cache control setting ('none' to disable). ### Request Example ```javascript // Basic usage var canvas = document.getElementById("canvas"); var html = '
Hello World
'; rasterizeHTML.drawHTML(html, canvas) .then(function(result) { console.log("Rendered successfully!"); }) .catch(function(error) { console.error("Rendering failed:", error.message); }); // Without canvas rasterizeHTML.drawHTML(html).then(function(result) { var ctx = canvas.getContext('2d'); ctx.drawImage(result.image, 10, 25); }); // With options rasterizeHTML.drawHTML(html, canvas, { width: 800, height: 600, baseUrl: 'https://example.com/assets/', cache: 'none' }).then(function(result) { console.log("Rendered with custom viewport"); }); ``` ### Response #### Success Response (Promise resolves with an object) - **image** (HTMLImageElement or HTMLCanvasElement) - The rendered image or canvas. - **svg** (string) - The SVG representation of the rendered content. - **errors** (array) - An array of objects detailing any resource loading errors. #### Response Example ```json { "image": "", "svg": "...", "errors": [] } ``` ``` -------------------------------- ### Draw HTML to canvas context Source: https://github.com/cburgmer/rasterizehtml.js/wiki/Examples Uses a promise-based approach to retrieve a render result and manually draw the resulting image onto a canvas context. ```javascript var canvas = document.getElementById("canvas"), context = canvas.getContext('2d'), html = "Some more HTML"; rasterizeHTML.drawHTML(html).then(function (renderResult) { context.drawImage(renderResult.image, 10, 25); }); ``` -------------------------------- ### Set Font Size for Div Element Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/fixtures/testFragment.html Apply a specific font size to a div element that also has the 'teST' class. This demonstrates specificity in CSS. ```css div.teST { font-size: 10px; } ``` -------------------------------- ### Render HTML to Canvas Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/README.md Draws a string of HTML content onto a specified canvas element. ```js var canvas = document.getElementById("canvas"); rasterizeHTML.drawHTML('Some ' + 'HTML' + ' with an image ', canvas); ``` -------------------------------- ### rasterizeHTML.drawURL Source: https://github.com/cburgmer/rasterizehtml.js/wiki/API Renders a URL to the canvas. ```APIDOC ## rasterizeHTML.drawURL ### Description Draws the content of a URL to the canvas. ### Parameters #### Arguments - **url** (string) - Required - The URL to render. - **canvas** (HTML5 canvas node) - Optional - The target canvas element. - **options** (object) - Optional - Configuration options for rendering. ### Response #### Success Response - **renderResult** (object) - A promise that resolves with an object containing 'image', 'svg', and 'errors'. ``` -------------------------------- ### Render Page from URL to Canvas with rasterizeHTML.js Source: https://context7.com/cburgmer/rasterizehtml.js/llms.txt Use drawURL to load and render an HTML page from a URL to a canvas. Ensure the page is same-origin or has CORS enabled. JavaScript execution can be enabled with timeouts. ```javascript var canvas = document.getElementById("canvas"); // Basic URL rendering rasterizeHTML.drawURL("template.html", canvas) .then(function(result) { console.log("Page rendered successfully"); }) .catch(function(error) { if (error.message === "Unable to load page") { console.error("Could not load the URL - check same-origin policy"); } }); ``` ```javascript rasterizeHTML.drawURL("interactive-page.html", canvas, { executeJs: true, executeJsTimeout: 2000, // Wait up to 2 seconds for JS width: 1024, height: 768 }).then(function(result) { console.log("Page with JS rendered"); }); ``` ```javascript rasterizeHTML.drawURL("page-with-images.html", canvas) .then(function(result) { result.errors.forEach(function(err) { console.warn("Failed to load " + err.resourceType + ": " + err.url); // resourceType: 'image', 'stylesheet', 'backgroundImage', 'fontFace', 'script' }); }); ``` -------------------------------- ### Style Span Element with Float and Dimensions Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/fixtures/testFragment.html Configure a span element with the 'teST' class to float left, and set its width and height. This is useful for layout purposes. ```css span.teST { float: left; width: 100px; height: 100px; } ``` -------------------------------- ### Draw Document to canvas Source: https://github.com/cburgmer/rasterizehtml.js/wiki/API Renders a Document object onto the specified canvas. ```javascript rasterizeHTML.drawDocument( document [, canvas] [, options] ) ``` -------------------------------- ### Set Background Image on Active State Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/fixtures/testFragment.html Apply a background image when an element is in its active state. The background-size property is set to 100% to cover the element. ```css .bgimage:active { background-image: url("rednblue.png"); background-size: 100%; } ``` -------------------------------- ### rasterizeHTML.drawHTML Source: https://github.com/cburgmer/rasterizehtml.js/wiki/API Renders an HTML string to the canvas. ```APIDOC ## rasterizeHTML.drawHTML ### Description Draws a provided HTML string to the canvas. ### Parameters #### Arguments - **html** (string) - Required - The HTML string to render. - **canvas** (HTML5 canvas node) - Optional - The target canvas element. - **options** (object) - Optional - Configuration options for rendering. ``` -------------------------------- ### Define Custom Font Face Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/fixtures/testFragment.html Use @font-face to define a custom font family and specify its source. Ensure the font file is accessible. ```css @font-face { font-family: "RaphaelIcons"; src: url('raphaelicons-webfont.woff'); } ``` -------------------------------- ### rasterizeHTML.drawDocument Source: https://github.com/cburgmer/rasterizehtml.js/wiki/API Renders a Document object to the canvas. ```APIDOC ## rasterizeHTML.drawDocument ### Description Draws a Document object to the canvas. ### Parameters #### Arguments - **document** (Document) - Required - The Document object to render. - **canvas** (HTML5 canvas node) - Optional - The target canvas element. - **options** (object) - Optional - Configuration options for rendering. ``` -------------------------------- ### Basic Body Margin Reset Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/diffHelperPage.html A simple CSS rule to reset the default margin for the HTML body element. ```css body { margin: 0; } ``` -------------------------------- ### Draw HTML to canvas Source: https://github.com/cburgmer/rasterizehtml.js/wiki/Examples Renders an HTML string directly into a specified canvas element. ```javascript var canvas = document.getElementById("canvas"), html = "Some HTML"; rasterizeHTML.drawHTML(html, canvas); ``` -------------------------------- ### Apply Vertical Alignment Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/fixtures/testFragment.html Set the vertical alignment of an element to top. This is useful for aligning content within containers. ```css .teST { vertical-align: top; } ``` -------------------------------- ### Render Image Difference to Body Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/diffHelperPage.html Appends a canvas element representing the difference between two images to the document's body. Assumes `imagediff.diff` and `canvasForImageCanvas` are available. ```javascript var renderDiff = function (image1, image2) { var canvas = canvasForImageCanvas( imagediff.diff(image1, image2), ); document.getElementsByTagName("body")[0].appendChild(canvas); }; ``` -------------------------------- ### drawDocument - Render Document Object to Canvas Source: https://context7.com/cburgmer/rasterizehtml.js/llms.txt Renders a Document or DocumentFragment object directly to canvas. Useful when you already have a parsed DOM structure or want to render parts of the current page. ```APIDOC ## drawDocument - Render Document Object to Canvas ### Description Renders a Document or DocumentFragment object directly to canvas. Useful when you already have a parsed DOM structure or want to render parts of the current page. ### Method `rasterizeHTML.drawDocument(doc, canvas, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **doc** (Document or DocumentFragment) - Required - The DOM document or fragment to render. - **canvas** (HTMLCanvasElement) - Optional - The canvas element to draw on. If not provided, an image object is returned. - **options** (object) - Optional - Configuration options for rendering. - **width** (number) - The width of the rendering viewport. - **height** (number) - The height of the rendering viewport. ### Request Example ```javascript var canvas = document.getElementById("canvas"); // Render an existing document element var doc = document.implementation.createHTMLDocument("Test"); doc.body.innerHTML = '

Dynamic Document

'; rasterizeHTML.drawDocument(doc, canvas) .then(function(result) { console.log("Document rendered"); }); // Render a document fragment var fragment = document.createDocumentFragment(); var div = document.createElement('div'); div.innerHTML = '

Fragment content

'; fragment.appendChild(div); rasterizeHTML.drawDocument(fragment, canvas, { width: 400, height: 300 }); // Clone and render part of current page var clonedElement = document.getElementById("content").cloneNode(true); var tempDoc = document.implementation.createHTMLDocument(""); tempDoc.body.appendChild(clonedElement); rasterizeHTML.drawDocument(tempDoc, canvas); ``` ### Response #### Success Response (Promise resolves with an object) - **image** (HTMLImageElement or HTMLCanvasElement) - The rendered image or canvas. - **svg** (string) - The SVG representation of the rendered content. - **errors** (array) - An array of objects detailing any resource loading errors. #### Response Example ```json { "image": "", "svg": "...", "errors": [] } ``` ``` -------------------------------- ### Render Document Object to Canvas with rasterizeHTML.js Source: https://context7.com/cburgmer/rasterizehtml.js/llms.txt Use drawDocument to render a Document or DocumentFragment object to canvas. This is useful for rendering pre-parsed DOM structures or parts of the current page. ```javascript var canvas = document.getElementById("canvas"); // Render an existing document element var doc = document.implementation.createHTMLDocument("Test"); doc.body.innerHTML = '

Dynamic Document

'; rasterizeHTML.drawDocument(doc, canvas) .then(function(result) { console.log("Document rendered"); }); ``` ```javascript var fragment = document.createDocumentFragment(); var div = document.createElement('div'); div.innerHTML = '

Fragment content

'; fragment.appendChild(div); rasterizeHTML.drawDocument(fragment, canvas, { width: 400, height: 300 }); ``` ```javascript // Clone and render part of current page var clonedElement = document.getElementById("content").cloneNode(true); var tempDoc = document.implementation.createHTMLDocument(""); tempDoc.body.appendChild(clonedElement); rasterizeHTML.drawDocument(tempDoc, canvas); ``` -------------------------------- ### Change Text Color on Hover Source: https://github.com/cburgmer/rasterizehtml.js/blob/master/test/fixtures/testFragment.html Modify the text color of an element when the mouse hovers over it. This provides visual feedback to the user. ```css .webfont:hover { color: #f52887; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.