Renders HTML into the browser's canvas

Overview

rasterizeHTML.js

NPM version

Renders HTML into the browser's canvas.

See the API.

Install

$ npm install rasterizehtml

Then include a script tag with node_modules/rasterizehtml/dist/rasterizeHTML.allinone.js or require through browserify.

Example

var canvas = document.getElementById("canvas");
rasterizeHTML.drawHTML('Some ' +
                       '<span style="color: green; font-size: 20px;">HTML</span>' +
                       ' with an image <img src="someimg.png">',
                       canvas);

See the examples page. The code also ships with examples, make sure to run npm test first to compile the library.

How does it work

For security reasons rendering HTML into a canvas is severly limited. Firefox offers such a function via ctx.drawWindow(), but only with Chrome privileges (see https://developer.mozilla.org/en/Drawing_Graphics_with_Canvas).

As described in http://robert.ocallahan.org/2011/11/drawing-dom-content-to-canvas.html and https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas however it is possible by embedding the HTML into an SVG image as a <foreignObject> and then drawing the resulting image via ctx.drawImage().

In addition SVG is not allowed to link to external resources and so rasterizeHTML.js will load external images, fonts and stylesheets and store them inline via data: URIs (or inline style elements respectively).

Limitations

All resources (HTML page, CSS, images, fonts and JS) that are needed for drawing the page can only be loaded if from the same origin, unless techniques like CORS are used. I.E. drawURL() can only load pages from the same domain as the current page and all draw methods can equally only embed styling and images from that domain.

The code is tested under Firefox, Chrome & Safari.

There's basic support for Microsoft Edge, however it will not work under any version of Internet Explorer.

Also the individual browsers still have some issues when rendering SVGs with embedded HTML to the canvas.

The full list of limitations is here.

TypeScript

Import type definitions as follows:

import * as rasterizeHTML from 'rasterizehtml';

Development

Run npm test.

For tests against individual browsers run python3 -m http.server and open http://localhost:8000/test/SpecRunner.html.

Where is it used?

  • CSS Critic, a lightweight tool for regression testing of Cascading Style Sheets
  • ...
Comments
  • Intensive canvas refresh makes the previous frame not cleared before drawing another frame in canvas.

    Intensive canvas refresh makes the previous frame not cleared before drawing another frame in canvas.

    Hey first of all I must say I'm glad and thankful that you made this powerful library.

    So I was using this to render some text to canvas and use some jQuery UI slider to toggle the font size. It worked well until I tested on an abusive behavior. When I slide the slider quickly from one value to another, the canvas render the next html without clearing the previous image. I'll post a picture below and some snippet if you need one. Is there anything I can do to tweak the performance? screen shot 2015-10-31 at 11 40 49 am

    opened by tsambora 11
  • Add font-size to root <svg> to support proper rem sizing

    Add font-size to root to support proper rem sizing

    I noticed an issue that the element and font sizing in the rasterized version of some pages is oddly different from the displayed page. After a bit of investigation, I found that the size of elements with properties specified in CSS3 rem units is determined based on the font-size of the root element which, when appearing in an SVG document, this is the root <svg> element rather than the <html> element which appears inside <foreignObject>.

    To support such pages, this pull request attempts to copy the font-size from the HTML document root to the SVG document root using getComputedStyle with fallback to currentStyle and style if neither of the others work (to support detached documents, particularly for testing).

    I'd appreciate your thoughts on it. Thanks, Kevin

    opened by kevinoid 11
  • Rendering URL fails

    Rendering URL fails

    Hi :) im trying to render a web page in large size, but the code doesnt work for me, im including rasterizeHTML.allinone.js ,declaring a Canvas ,and Calling: rasterizeHTML.drawURL("http://cnn.com", canvas, {cache: false, executeJs: true});

    any tips?

    opened by javismiles 10
  • CSS is ignored when rasterizing a DOM element

    CSS is ignored when rasterizing a DOM element

    Hello! I'm trying to render a single div from the DOM using the following code:

    const element = document.querySelector(".toRasterize"); rasterizeHTML.drawDocument(element, canvas)
    

    But the canvas created has no styling. However, when I render the entire document using rasterizeHTML.drawDocument(document, canvas), everything works fine.

    Is there something I'm missing here?

    opened by remidej 9
  • SVGStyleElement.sheet is undefined on iOS

    SVGStyleElement.sheet is undefined on iOS

    Hi, I am trying to get this plugin working with Cordova on iOS. It is crashing in function replaceSimpleSelectorsBy on this line because styleElement.sheet is undefined for elements with type SVGStyleElement on iOS.

    Do you have any idea how to fix it?

    opened by knuhol 9
  • Data URI Callback for save as file

    Data URI Callback for save as file

    Hi, i was implement rasterizeHTML to render div in current document using drawHTML. I got the result, but i need result as data URI/base_64 to save it as file.

    on response callback, image src that uses blob URL. i try convert it to data using this tutorial, but the return always empty. http://stackoverflow.com/questions/14952052/convert-blob-url-to-normal-url

    any solutions?

    opened by riskihajar 9
  • Inline SVG not rendering in the output

    Inline SVG not rendering in the output

    I'm using rasterizeHTML to convert my WYSIWYG editor to image. So far so good. But when I'm trying to convert the artboard with inline SVG, the images doesn't get generated. A sample SVG code I'm using is given below

    <svg width="300px" height="300px" viewBox="0 0 100 100" preserveAspectRatio="none"> <ellipse fill="#fff" stroke="#231F20" stroke-width="0.5" stroke-miterlimit="10" stroke-dasharray="2" cx="50" cy="50" rx="40.54" ry="40.584"></ellipse> </svg>

    Is there any code change that can be done to import the SVG to the canvas? The SVG is hardcoded and not from a cross-origin. Or is there any workaround for this.

    opened by AshwinTayson 8
  • Load fonts

    Load fonts

    How can I load fonts that are in an external file? The files are in the same cakePHP project, so I don't think that the problem is about cross origin. I'm appending a string containing the css rules to the begining of the HTML string that I send for rasterizeHML. I tried putting the font-face rule at the begining of the string but it doesn't seem to work. How is the best way to do this? What can I be doing wrong? It is possible that being in a local server (Wamp) is the problem?

    Here is an example of my code:

    html = $("#exportar_container").html().trim();
    html = "<style>@font-face { font-family: 'DIN'; src: url('/website/fonts/DIN/DINBold.ttf'); src: url('/website/fonts/DIN/DINBold.woff') format('woff'), url('/website/fonts/DIN/DINBold.svg') format('svg'), url('/website/fonts/DIN/DINBold.ttf') format('truetype');} #exportar { font-family: 'DIN';} </style>" + html;
    
    rasterizeHTML.drawHTML(html, canvas);
    

    Thank you for any ideas or suggestions!

    opened by csbatista 8
  • webpack require prompt `cssMediaQuery` and `sanedomparsererror ` not found

    webpack require prompt `cssMediaQuery` and `sanedomparsererror ` not found

    excuse me, When I require rasterizeHTML, it did not work normally... what should i do?

    import RasterizeHTML from 'rasterizeHTML';
    
    ./~/rasterizeHTML/dist/rasterizeHTML.js
    Module not found: Error: Cannot resolve module 'cssMediaQuery'
    ...
    .../node_modules/cssMediaQuery doesn't exist...
    ...
    ./~/rasterizeHTML/dist/rasterizeHTML.js
    Module not found: Error: Cannot resolve module 'sanedomparsererror'
    
    opened by QingWei-Li 8
  • Webkit fails to render SVGs

    Webkit fails to render SVGs

    Including SVGs in the HTML leads to a parsing error. Is it possible to add SVG support?

    Example SVG:

    <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
       <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" />
    </svg> 
    
    opened by koppor 8
  • Better to cleanup *after* callback?

    Better to cleanup *after* callback?

    Wouldn't it make more sense to call the successCallback before calling cleanUp() in module.renderSvg(), so that the callback can make use of the blob URL if needed?

    opened by admbtlr 8
  • Iframe cannot be opened in Firefox insecure context

    Iframe cannot be opened in Firefox insecure context

    We are using this project in a Firefox/Chrome web extension. RasterizeHTML is included as a content script (ie. insecure context).

    PROBLEM: Firefox is blocking Rasterize from opening an iFrame in the insecure context. Basically, all actions on the iframe.contentDocument are banned: open, write, close, etc.

    I fixed the problem locally by changing the following:

    iframe.contentDocument.open()
    ...
    iframe.contentDocument.write("<!DOCTYPE html>");
    iframe.contentDocument.write(html);
    iframe.contentDocument.close();
    

    to: iframe.srcdoc = `<!DOCTYPE html>${html}`;

    We cannot use Rasterize from the extension's background scripts (ie. from a secure context) because in Chrome manifest V3, background scripts will not have access to the DOM.

    Would it be possible for someone at Rasterize to address this issue, so that we can use your CDN directly with no security errors in FF insecure context?

    opened by chladnefazole 0
  • Failing for large svg's in iOS

    Failing for large svg's in iOS

    Hi,

    Large files are failing on iOS devices. We are converting our images into data Uri's and then appending them into svg's. Sample: https://jsfiddle.net/1ratc76L/5/

    Is there any way we can bypass appending data uri and apss blob's directly, or any other way to make it work. Our production code generates empty outputs in those cases.

    opened by Saahiljeet-Singh 1
  • Typescript: drawHTML is not exported by node_modules/rasterizehtml/dist/rasterizeHTML.js

    Typescript: drawHTML is not exported by node_modules/rasterizehtml/dist/rasterizeHTML.js

    Any helps?

    I using rollup to build my system Screen Shot 2021-10-24 at 1 09 37 AM

    This is my code

    import * as rasterizeHTML from 'rasterizehtml’;
    const canvas = document.createElement('canvas');
    canvas.height = el.offsetHeight;
     canvas.width = el.offsetWidth;
                
    rasterizeHTML.drawHTML(el.outerHTML, canvas);
    reviewImage = canvas.toDataURL('image/jpeg');
    
    opened by nhatlang19 1
  • Black image

    Black image

    All I can get is a black image after call to rasterizeHTML.drawHTML(document, canvas) Note: No error is given. It's my document fault or am I missing some needed options?

    opened by clobotorre 1
  • Insert rasterizeHTML image to jsPDF document

    Insert rasterizeHTML image to jsPDF document

    Hi

    I started working with rasterizeHTML and i get the renderResult.image object. Im trying to insert the image into a jsPDF document but to my regret with no success, anybody knows how to achieve this goal?

    opened by omeriko 0
Releases(1.3.1)
  • 1.3.1(Jan 16, 2022)

    Bug fixes

    • Fix issue with errors in Chrome when simulating pseudo-class selectors hover/active/focus/target if executeJs set to true #219

    All in one bundle

    • inlineresources dependency bumped to 1.0.1
    Source code(tar.gz)
    Source code(zip)
  • 1.3.0(Mar 18, 2018)

    • Use ES6 Promises instead of own Promise implementation (#154)
    • Typescript type annotations (#197), by @orentrutner
    • Drop workarounds as Chrome ships with fixes by now
      • Media query workaround for em values
      • CSSOM dropped as dependency

    Bug fixes

    • Blob fallback is now correctly triggered
    • Fix incorrect canvas sizing when box-sizing is used (#187)
    Source code(tar.gz)
    Source code(zip)
  • 1.2.4(Oct 30, 2016)

  • 1.2.3(Oct 13, 2016)

  • 1.2.2(Feb 23, 2016)

    Bug fixes

    • Bump dependencies for allinone build
      • Fixes issue where CSS in a background tab is flaky.
      • @font-face rules in newer Chrome versions would result in an empty url().
    Source code(tar.gz)
    Source code(zip)
  • 1.2.1(Nov 26, 2015)

    Bug fixes

    • Module names for AMD did not reflect their names in npm as required by webpack (#106)
    • Chrome and Safari would not correctly zoom elements with position: relative (#109)

    Both fixes thanks to @QingWei-Li

    Source code(tar.gz)
    Source code(zip)
  • 1.2.0(Oct 3, 2015)

    • Support for :target selector activation.
    • On parsing errors the originalError is going to be provided for detailed information (see API, #102).

    Bug fixes

    • Fix issue with media queries under Microsoft Edge.
    • Fix :focus action incorrectly being cascaded up the DOM tree.
    Source code(tar.gz)
    Source code(zip)
  • 1.1.0(Mar 26, 2015)

    • A workaround is provided for a media query issue in Chrome/Safari where em values will be incorrectly applied (https://code.google.com/p/chromium/issues/detail?id=404470).

    Bug fixes

    • Fix empty space showing on the right side (issue #95) in browsers under Linux.
    • Fix scrollbar showing on Chrome/Chromium under Linux.
    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Mar 1, 2015)

    • Reading back pixels from the canvas is now supported in Chrome (https://github.com/cburgmer/rasterizeHTML.js/issues/88).
    • Additionally provides the internal SVG with the render result (by @Venemo, https://github.com/cburgmer/rasterizeHTML.js/pull/68).
    • A focus event can now be simulated via option focus.

    Bug fixes

    • Fixes size of elements specified via rem (by @kevinoid, https://github.com/cburgmer/rasterizeHTML.js/pull/75).
    • Fixes uppercase type (HTML tag) CSS selectors (https://github.com/cburgmer/rasterizeHTML.js/issues/63).
    • Viewport size calculation incorrectly triggered the browser's quirks mode.
    • Complex selectors with :hover/:active would break when hover or active option was given.
    • Hover and active options now try to be as minimally invasive as possible to work around illegal selectors triggering Chrome to fail.

    API changes

    • The previous callback option was deprecated and has been removed.
    • The cache option supported the boolean value false, this has now been removed.

    Limitations

    The list of limitations has been cleaned up and extended.

    Source code(tar.gz)
    Source code(zip)
  • 0.9.3(Aug 26, 2014)

  • 0.9.2(Aug 26, 2014)

    Bug fix

    • Viewport size now honours the zoom option (#64).
    • Margins of the rendered content now don't collapse with the outside host document (Chrome & Safari, #65).
    • Fix active & hover option in drawURL() throwing a TypeError in Firefox (#66).
    • Support window.matchMedia (#71).

    Other changes:

    • The Git repository does not host the packaged sources anymore. The prefered way of installation is through npm install rasterizehtml and including node_modules/rasterizehtml/dist/rasterizeHTML.allinone.js.
    • Experimental clipping support: The rendered document can be clipped around a given element by passing clip: '.mySelector' as an option.
    • A workaround for browsers with flaky resource loading has been removed, as all up-to-date browsers now seem to correctly handle resources.
    • Integration tests have been stabilized to pass on Linux systems, too.
    Source code(tar.gz)
    Source code(zip)
  • 0.9.1(Jun 6, 2014)

  • 0.9.0(Apr 23, 2014)

    • A new option zoom allows the displayed content to be zoomed.
    • When executing JavaScript (executeJs set to true), drawing will now wait for pending XMLHttpRequests to finish.
    • An Invalid source error is now thrown if the input has invalid syntax. Before, this just resulted in the more general Error rendering page being thrown.
    • The npm package is now requirable via browserify. (Fixes #54)
    • The all-in-one bundle now doesn't pollute the global namespace with its dependencies. If you relied on them being pulled in through rasterizeHTML.allinone.js in the past, you will need to load those dependencies yourself. (Fixes #52)
    • The rasterizeHTML.js distributable now comes with a proper UMD header and does not pollute the namespace with internal modules (see #52). If you relied on specific internal code (the API documentation did try to discourage you from doing so), you have two options:
      • Check if one of the dependencies rasterizeHTML.js is using is what you are actually looking for.
      • Raise a ticket to discuss whether that functionality should be (re-)exposed.
    Source code(tar.gz)
    Source code(zip)
  • 0.8.0(Feb 17, 2014)

    • New API: All methods now return a promise and results can be yielded like rasterizeHTML.drawURL().then(function (renderResult) { ... })
    • The old callback style is now deprecated in favour of the promises style.
    • If rendering fails completely, only the actual failing error is now reported.
    • Fix "!important" not being correctly transfered when inlining background images.
    • Fix same mime type being used for several alternate font face sources.
    Source code(tar.gz)
    Source code(zip)
  • 0.7.0(Dec 12, 2013)

    • The resulting image now reflects the correct content size, i.e. it will be bigger than the defined viewport if content overflows.
    • New options to simulate a :hover and :active effect on elements by passing a selector to options hover and active. See examples/pseudoClasses.html.
    • Allow AJAX in the executed page to be based on the correct base URL.
    • Correctly render input element values changed through script manipulation.
    • Fix issue with script attributes being stripped on inlining.
    • Fix issue with CSS import paths not being based relatively to the referencing document's URL.
    • Fix issue with font face defintions being stripped of font-weight and font-style values.
    Source code(tar.gz)
    Source code(zip)
  • 0.6.0(Nov 25, 2013)

    New minor version with many fixes for improved stability

    • Fixes handling of relative base paths
    • Fixes rendering of non-UTF8 pages (#44)
    • Fixes issue with attributes missing from top-level element
    • Fixes issue with dashes in comments
    • Fixes issue with closing tags in script content
    • Fixes issue with quoting of special characters in element attributes
    • Fixes issue with invalid ASCII control characters
    • Changed dependencies
    Source code(tar.gz)
    Source code(zip)
  • 0.5.1(Nov 2, 2013)

  • 0.5.0(Oct 30, 2013)

    • Fixes issues with certain HTML in Chrome & Safari
    • Fixes an error when parsing CSS in Chrome (fixed upstream)
    • Optional caching of performance critical parts with an extended 'cache' option
    • Only loads scripts if JS in the page is going to be executed
    Source code(tar.gz)
    Source code(zip)
Owner
Christoph Burgmer
@cburgmer on Twitter
Christoph Burgmer
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser

Fabric.js Fabric.js is a framework that makes it easy to work with HTML5 canvas element. It is an interactive object model on top of canvas element. I

Fabric.js 23.6k Jan 3, 2023
HTML5 Canvas Gauge. Tiny implementation of highly configurable gauge using pure JavaScript and HTML5 canvas. No dependencies. Suitable for IoT devices because of minimum code base.

HTML Canvas Gauges v2.1 Installation Documentation Add-Ons Special Thanks License This is tiny implementation of highly configurable gauge using pure

Mykhailo Stadnyk 1.5k Dec 30, 2022
Konva.js is an HTML5 Canvas JavaScript framework that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.

Konva Konva is an HTML5 Canvas JavaScript framework that enables high performance animations, transitions, node nesting, layering, filtering, caching,

konva 8.7k Jan 8, 2023
React + Canvas = Love. JavaScript library for drawing complex canvas graphics using React.

React Konva React Konva is a JavaScript library for drawing complex canvas graphics using React. It provides declarative and reactive bindings to the

konva 4.9k Jan 9, 2023
Canvas rendering library, Sprite manipulation of canvas

el-canvas Canvas rendering library, Sprite manipulation of canvas hello world <div id="app"><div></div></div> yarn add elem-canvas or npm i

null 15 Apr 13, 2022
Bring data to life with SVG, Canvas and HTML. :bar_chart::chart_with_upwards_trend::tada:

D3: Data-Driven Documents D3 (or D3.js) is a JavaScript library for visualizing data using web standards. D3 helps you bring data to life using SVG, C

D3 103.8k Jan 3, 2023
Interactive visualizations of time series using JavaScript and the HTML canvas tag

dygraphs JavaScript charting library The dygraphs JavaScript library produces interactive, zoomable charts of time series: Learn more about it at dygr

Dan Vanderkam 3k Jan 3, 2023
JAVASCRIPT library with which you can easily draw CANVAS HTML

easycanvas Quick start Documentation: gaidadei.ru/easycanvas Download: gaidadei.ru/easycanvas/easyc.zip Buy premium: gaidadei.ru/easycanvas/premium (A

null 18 Nov 12, 2022
Lightweight, interactive planning tool that visualizes a series of tasks using an HTML canvas

Planner Lightweight, interactive planning tool that visualizes a series of tasks using an HTML canvas. Try it yourself at plannerjs.dev Plans created

Brian Vaughn 512 Jan 2, 2023
HTML Canvas game for Vivatech Gamejam of March 2022.

Viva Tech Gamejam A HTML Canvas game made in 2 days for the Vivatech Gamejam of March 22. Requirements Nodejs and Yarn. If you're on MacOS and have Ho

Antoine Oddoz 3 Mar 29, 2022
Demonstration of liquid effect on HTML Canvas using Matter.js and SVG Filters (Blur + Contrast)

Canvas Liquid Effect Demonstration of liquid (or gooey) effect on HTML Canvas using Matter.js and SVG Filters (feGaussianBlur and feColorMatrix). DEMO

Utkarsh Verma 78 Dec 24, 2022
Simple HTML5 Charts using the tag

Simple yet flexible JavaScript charting for designers & developers Documentation Currently, there are two versions of the library (2.9.4 and 3.x.x). V

Chart.js 59.4k Jan 7, 2023
The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas. Created by @lehni & @puckey

Paper.js - The Swiss Army Knife of Vector Graphics Scripting If you want to work with Paper.js, simply download the latest "stable" version from http:

Paper.js 13.5k Dec 30, 2022
🔥 JavaScript Library for HTML5 canvas based heatmaps

heatmap.js Dynamic Heatmaps for the Web. How to get started The fastest way to get started is to install heatmap.js with bower. Just run the following

Patrick Wied 5.9k Jan 2, 2023
Financial lightweight charts built with HTML5 canvas

Lightweight Charts Demos | Documentation | Discord community TradingView Lightweight Charts are one of the smallest and fastest financial HTML5 charts

TradingView, Inc. 5.8k Jan 9, 2023
Flat, round, designer-friendly pseudo-3D engine for canvas & SVG

Zdog Round, flat, designer-friendly pseudo-3D engine View complete documentation and live demos at zzz.dog. Install Download zdog.dist.min.js minified

Metafizzy 9.5k Jan 3, 2023
🍞🎨 Full-featured photo image editor using canvas. It is really easy, and it comes with great filters.

Full featured image editor using HTML5 Canvas. It's easy to use and provides powerful filters. Packages toast-ui.image-editor - Plain JavaScript compo

NHN 5.7k Jan 6, 2023
🦍• [Work in Progress] React Renderer to build UI interfaces using canvas/WebGL

React Ape React Ape is a react renderer to build UI interfaces using canvas/WebGL. React Ape was built to be an optional React-TV renderer. It's mainl

Raphael Amorim 1.5k Jan 4, 2023
Canvas

Installation $ npm install knights-canvas Example GoodBye const ling = require("knights-canvas"), const fs = require('fs'); const image = await new

null 5 Feb 16, 2022