GithubHelp home page GithubHelp logo

niklasvh / html2canvas Goto Github PK

View Code? Open in Web Editor NEW
30.3K 509.0 4.8K 114.55 MB

Screenshots with JavaScript

Home Page: https://html2canvas.hertzen.com/

License: MIT License

JavaScript 11.51% HTML 29.98% CSS 0.26% TypeScript 58.25%
javascript screenshot dom

html2canvas's Introduction

html2canvas

Homepage | Downloads | Questions

Gitter CI NPM Downloads NPM Version

JavaScript HTML renderer

The script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.

How does it work?

The script renders the current page as a canvas image, by reading the DOM and the different styles applied to the elements.

It does not require any rendering from the server, as the whole image is created on the client's browser. However, as it is heavily dependent on the browser, this library is not suitable to be used in nodejs. It doesn't magically circumvent any browser content policy restrictions either, so rendering cross-origin content will require a proxy to get the content to the same origin.

The script is still in a very experimental state, so I don't recommend using it in a production environment nor start building applications with it yet, as there will be still major changes made.

Browser compatibility

The library should work fine on the following browsers (with Promise polyfill):

  • Firefox 3.5+
  • Google Chrome
  • Opera 12+
  • IE9+
  • Safari 6+

As each CSS property needs to be manually built to be supported, there are a number of properties that are not yet supported.

Usage

The html2canvas library utilizes Promises and expects them to be available in the global context. If you wish to support older browsers that do not natively support Promises, please include a polyfill such as es6-promise before including html2canvas.

To render an element with html2canvas, simply call: html2canvas(element[, options]);

The function returns a Promise containing the <canvas> element. Simply add a promise fulfillment handler to the promise using then:

html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
});

Building

You can download ready builds here.

Clone git repository:

$ git clone git://github.com/niklasvh/html2canvas.git

Install dependencies:

$ npm install

Build browser bundle

$ npm run build

Examples

For more information and examples, please visit the homepage or try the test console.

Contributing

If you wish to contribute to the project, please send the pull requests to the develop branch. Before submitting any changes, try and test that the changes work with all the support browsers. If some CSS property isn't supported or is incomplete, please create appropriate tests for it as well before submitting any code changes.

html2canvas's People

Contributors

ahebrank avatar andyedinborough avatar arrix avatar balupton avatar bensho avatar cobexer avatar cthackers avatar cybershadow avatar danalstadt avatar ddrscott avatar djfarrelly avatar earshinov avatar ekoopmans avatar felfert avatar fhyoga avatar flyskyko avatar garaboncias avatar gatapia avatar hyojin avatar jayaddison avatar matthias-christen avatar moyuscript avatar niklasvh avatar oleksiy-nesterov avatar pauljthompson avatar rickbetting avatar simonpinn avatar ssafejava avatar usmonster avatar val1984 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

html2canvas's Issues

$(a).css is not a function

Any idea why I am getting this weird "$(a).css is not a function" in firebug when trying to render a capture of a joomla created site?

Enabling logging I get in firebug:

html2canvas: Preload starts: finding background-images
html2canvas.Util.Children failed with exception: $(a).contents is not a function
$(a).css is not a function

EDIT: with other frameworks there can be conflict.

Replace $ -> jQuery in html2canvas, and call jQuery.noConflict() right after inclusion. Fixed...

Any guide on how to get the proxy working?

Hi,

I've gotten the code and currently the client side runs (basically i downloaded the codebase, put it in /var/www/, and pointed my browser to localhost/html2canvas/screenshot.html

I am not sure if there is anything more involved that i need to be doing in order to get this to run. Some pointers would be very much appreciated :)

Can't wait to try it out :)

Jason

[Enhancement] Generators getColors-function

https://github.com/niklasvh/html2canvas/blob/master/src/Generate.js#L34

current function:

    function getColors(input) {      
        var j = -1, 
        color = '', 
        chr;
        while( j++ < input.length ) {
            chr = input.charAt( j );
            if (chr === ')') {
                color += chr;
                steps.push( color );
                color = '';
                j = input.indexOf(",", j) + 1;
                if (j === 0) {
                    break;
                }
            //  while (j++ < input.length && input.charAt( j ) !== ',') {}
            } else {
                color += chr;
            }
        }
    }

"enhanced"

    function getColors(input) {
        var colors = input.match(/#[a-fA-F0-9]{3,6}|rgb\s*\(\s*\d{0,3}\s*,\s*\d{0,3}\s*,\s*\d{0,3}\s*\)/g),
        for(i = 0, len = colors.length; i < len; i+=1)
            steps.push(colors[i]);
    }

multiple background images

Love this! The test console seems to fail when reaching a site with multiple css3 background images using the short hand background syntax.

background: url(/wp-content/uploads/2011/07/header_texture.jpg) repeat-x center top, url(/wp-content/uploads/2011/07/redtexture.jpg) repeat center 11px

Where is build/html2canvas.js?

The example calls on two js files:

<script type="text/javascript" src="build/html2canvas.js?221"></script>
<script type="text/javascript" src="build/jquery.plugin.html2canvas.js"></script>

both which are not in the project....

Use JavaScript 'new Image()' object instead of proxy when available.

Is there a reason why we cannot use something like:
loadImage(url, callback) {
var img = new Image();
img.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
callback(canvas.toDataURL('image/png'));
};
img.src = url;
}

This would save the need for a proxy no?

Note: I have not tried this, I don't know the limitations (x-domain, how to handle css backgrounds, etc). So this could be totally stupid, but I thought I'd mention it in case someone knows why this is not a good idea. Save me the effort of trying.

Thanks

new ver question about canvas img

hello
Like in older version i could make smth like this
"var oImg = renderer.canvas.toDataURL("image/png");"

I need to take canvas and save it on the server after created but i need to save it in PNG so i was doing this in
in plugin.html2canvas.js
ready: function(renderer) {
}
How to take this in new ver?

NIKLASVH - Is in new version fixed issue with html select ?

Rendering a Single Element Produces Oversized Canvas

I am attempting to render a single element (a div in my case). When I do this I end up with a canvas that is the size of the entire body instead of the single element. It would be ideal if the canvas were the size of the element passed in.

Textareas don't have user line breaks when screenshotted

Hi -

If I put in text with returns in it, the screenshot doesn't contain the returns [just looks collapsed in a string with the carriage returns]. I lasted pulled this code a few [say 3] mos ago. Has that been fixed or is it still an issue?

Support of Canvas

html2canvas doesn't support Canvas.
Is this feature part of the roadmap ?
I know that SVG support is planned according to the author's Tweeter page.

Html select diffrents in FF and Chrome

Hello.
First of all big thanks for this library . I have a problem with displaying html select on screen. In chrome it looks ok but on FF is makeing strange sign it looks like is trying to put all select options in one box and it's makeing bule box on not selected options. In my opinion it should take a first selectedindex.. I change the linies from 922 in html2canvas.js smth like this
f (el.nodeName == "SELECT")
{

     if (el.selectedIndex == null)
       {
        var textValue = el.options[0].text;

       } 
       else var textValue = el.options[el.selectedIndex].text;

    // TODO increase accuracy of text position
   // var textValue = el.options[el.selectedIndex].text;
} 

but this isnt working. Please help

Error to return content from proxy (external images)

Hi! First, congratulations by code. I'm trying use it in a chrome extension to run in ContentScript.js. Happens that when exists external images in the webpage the canvas element isn't created and appears a message in the console: "Uncaught ReferenceError: html2canvas_[N] is not defined". Already try add http://html2canvas.appspot.com/ to permissions manifest, but, the error persists. I'm doing something wrong or is a project limitation?

Possible improvement: canvasWidth & canvasHeight

Hi, I'm totally new to your great script.
But I noticed something interesting about the canvas dimensions.
When a user sets them they should be honored IMHO.
Now your using whatever is bigger: The document or the user settings.
Example:

$('#target').html2canvas( {
            canvasHeight : 60,
            canvasWidth : 400
        });

I made the following edits in your code:
Line 63 and 64

        canvasHeight:null,

Line 1347 and 1348

    this.canvas.height = this.opts.canvasHeight || $(document).height();

Now the document sizes will be used if no user preference is given.

Let me know what you think of this!

DOMException: NOT_SUPPORTED_ERR in Opera 11.51

Trying any of the demos using Opera 11.51, instead of the script working like it does on Chrome, I just get this error:

[10/2/2011 1:00:52 AM] JavaScript - http://html2canvas.hertzen.com/demo.html
Event thread: DOMContentLoaded
Uncaught exception: DOMException: NOT_SUPPORTED_ERR
Error thrown at line 1187, column 24 in (a, renderItem) in http://html2canvas.hertzen.com/build/html2canvas.js:
ctx.fillText(renderItem.arguments[0],renderItem.arguments[1],renderItem.arguments[2]);
called from line 1814, column 8 in (arrayLoop, callbackFunc) in http://html2canvas.hertzen.com/build/html2canvas.js:
if (callbackFunc(i,arrayLoop[i]) === false)
called from line 1169, column 8 in (storageContext, ctx) in http://html2canvas.hertzen.com/build/html2canvas.js:
_.each(storageContext.ctx.storage,function(a,renderItem){
called from line 1312, column 8 in (queue, parentctx) in http://html2canvas.hertzen.com/build/html2canvas.js:
this.canvasRenderContext(storageContext,parentctx);
called from line 1347, column 4 in (queue) in http://html2canvas.hertzen.com/build/html2canvas.js:
this.canvasRenderStorage(queue,this.ctx);
called from line 1078, column 20 in (i, renderer) in http://html2canvas.hertzen.com/build/html2canvas.js:
_.canvasRenderer(queue);
called from line 1814, column 8 in (arrayLoop, callbackFunc) in http://html2canvas.hertzen.com/build/html2canvas.js:
if (callbackFunc(i,arrayLoop[i]) === false)
called from line 1072, column 4 in (queue) in http://html2canvas.hertzen.com/build/html2canvas.js:
this.each(this.opts.renderOrder.split(" "),function(i,renderer){
called from line 47, column 12 in (obj) in http://html2canvas.hertzen.com/build/html2canvas.js:
obj.Renderer(obj.contextStacks);
called from line 1693, column 4 in (element, stack) in http://html2canvas.hertzen.com/build/html2canvas.js:
this.opts.storageReady(this);

multiple background images

Love this! The test console seems to fail when reaching a site with multiple css3 background images using the short hand background syntax.

background: url(/wp-content/uploads/2011/07/header_texture.jpg) repeat-x center top, url(/wp-content/uploads/2011/07/redtexture.jpg) repeat center 11px

IE9 issue with Demo.html

Using niklasvh-html2canvas-1c44b94 with IE9 RTM 9.0.8112.16421. Demo.html does not work in this browser. But, demo2.html and demo3.html do.

not render dropdownlistbox and all input controls

Title says all, the library is not render any input control, including the select control, the dropdownlist.

I have run it and see it a lot and I have locate the main problem on

html2canvas.prototype.newText function, that at the point of bounds = range.getBoundingClientRect(); fail to read the bounds of the text that is inside a control.

Screenshot creation takes a long time.

Hi Niklas,

Thank you for creating this very useful javascript libraries to create the screenshot of html pages. I just started coding again after a long time and consider myself novice as far as web development goes.

For my use case, I am using the bookmarklet to create the screenshot of entire page. I then allow highlighting and cropping a certain section of the screenshot. But currently the screen shot creation takes quite some time. For example it takes anywhere from 4000 millisecond to 9000 millisecond to create the screenshot of www.yahoo.com. I spend some time on your source code and it seems to me the parsing takes the most amount of time. Is there a way I can optimize the performance so that I can bring down the screenshot creation time under 1 second.

I will really appreciate if you can provide some help on this or point me in the direction, so I can optimize this.

Regards!

Flash support?

Hi! First of all I want to say nice job niklasvh! I just want to know if it support flash already, because I have made some tries and it is not capturing flash stuff.

html2canvas.prototype.storageContext (simplified ?)

html2canvas.prototype.storageContext = function(width,height){
/**
* Simplified (readable ?) version by [email protected]
*/
var _this=this, _push=function(name)
{
var _slice=Array.prototype.slice; //TODO: extract higher
return function(){
this.storage.push(
{
type: "function",
name:name,
arguments:_slice.call(arguments)
});
}
};

_this.storage = [];
_this.width = width;
_this.height = height;
//this.zIndex;

_this.fillRect = _push("fillRect" /*x, y, w, h*/);      
_this.drawImage = _push("drawImage" /*image,sx,sy,sw,sh,dx,dy,dw,dh*/);     
_this.fillText = _push("fillText" /*currentText,x,y*/);

return _this;

}

How to render full of hidden part in 'overflow:auto' div

I have a div which contains all the elements that have to be converted into an image. And that div is set to 'overflow:auto'. I want to know how I can export all the elements(even hidden in the scrolling) to an image. I appreciate and welcome all your comments and answers...... Thanks in advance...

"execution exceeded timeout" on iPhone 3

I'm trying html2canvas to run in Safari for iPhone (iPhone; U; CPU iPhone OS 3_1_3) but I always obtain this timeout error during the page parsing by the prototyped function "parsing". In particular I obtain this error after about 35 recursive calls.
I tried inserting some setTimeout or setInterval, but I obtain lots of other errors and I'm not able to get the image

Options support

Are there any Options one can play with? Esp. the forced tooltip and click behaviour are a bit irritating.

Add support for text transform

<text id="ext-sprite-1152" zIndex="0" text="Feeds" font-family="tahoma, arial, verdana, sans-serif" font-weight="bold" font-size="11px" fill="rgb(4, 64, 140)" x="0" y="0" text-anchor="start" transform="matrix(0,1,-1,0,7,0)"><tspan x="0" dy="3.75">Feeds</tspan></text>

Screenshot.png , how to grab the canvas object

Hi everyone,
I'm trying to edit the bookmarklet in such a way that it makes the screenshot in jpg/png.

That is easy to make via :

var img    = canvas.toDataURL("image/png");

The problem is : I don't know how to intervene to grab the canvas object .

Can you suggest me how to realize the feature that I want? Which file should I modify, and how?

Thank you in advance

Correct way to get base64 "screenshot"?

I am trying to get the screenshot into a variable for later manipulation. It is currently working in FF only. Can someone please shed some light or steer me in the correct dir?

thanks!

function takesnap(body){
alert(1); // IE gets here...
    var preload = html2canvas.Preload(body, {
        "complete": function(images){
alert(10); // in IE doesnt get here....
            var queue = html2canvas.Parse(body, images);
            var canvas = $(html2canvas.Renderer(queue));
            var canvasElement = canvas[0];
            var a = canvasElement.toDataURL();
        }
    });
}
takesnap(document.body);

(I have tried with excanvas and flashcanvas, it doesnt give me any error, just doesnt get to the "complete" block... with logging enabled the console in IE9 shows that it is loading images, etc... it seems to just not process the "complete" action?)

PS: is this the easiest/best way to get a screenshot into a variable ('a' in this case)...

Add link/button to download image generated in console

Hi,
Just a request to add a link or button so that people can download the screenshot created in your console. I can't seem to right click on it, either, to download it.

Was hoping to use this in a class where students submit screenshots of their websites in progress.

Thanks,
-Doug

WRONG_DOCUMENT_ERR: DOM in Chrome

In the latest check-in (ff63511) the minified version throws an error in chrome WRONG_DOCUMENT_ERR.

Note: I am passing it the body from an iFrame, but the non-minified version works just fine. Below is where it breaks in the debugger.

10)){case 401:i="bold";break;case 400:i="normal"}c.setVariable("fillStyle",j);c.setVariable("font",a+" "+i+" "+t+" "+h+" "+g);c.setVariable("textAlign","left");a=b;for(h=g=0;h<m.length;h++){if(l!=="none"||d(m[h]).length!==0){if(D.rangeBounds)t=m[h],document.createRange?(i=document.createRange(),i.setStart(b,g),i.setEnd(b,g+t.length)):i=E.createTextRange(),i=i.getBoundingClientRect()?i.getBoundingClientRect():{};else{if(typeof a.nodeValue!=="string")continue;var x=a.splitText(m[h].length),y=a.parentNode,
'''

Limit preload images to the element only

Hello,

I am using "html2canvas" and it's really cool. In my use case, I don't need to create an image of the whole page, but instead I want to create an image of a certain element on the page. The image is generated correctly, but the whole process is quite long. I took a look to the source code and I found the following comment in "Preload.js" (line 23):

domImages = doc.images, // TODO probably should limit it to images present in the element only

So, can you confirm that the long execution time is due to the fact that all images on the page are treated, even if I want to create a snapshot of a single element on the page (like a

with some content and a couple of images)?

If so, do you think the "TODO" will be solved in version 0.34?

Thank you.

please drop all files in the build folder

I tried to merge together a few html2canvas repositories and discovered that there are some that have changes in the built files, so please remove them:
Benefits:

  • better change history
  • easier merging
  • removed the possibility for others to modify the built files (these changes are very bad to merge in a useful way)
  • from what i remember of the history of the html2canvas project there were some changes that fixed something only in the built files, those changes may be lost ... that has yet to be discovered

additionally a .gitignore file would be nice to avoid people adding that file again

This problem gets wore every time someone forks this repository, so please consider doing this ASAP

Safari Crash Issue

This line of code causes Safari to crash when rendering (at line 563 in the build):
text_align = text_align.replace(["-webkit-auto"],["auto"]);

I also tried removing the strings from the arrays, still crashes. I took out the line of code on my copy and it works.

See my comment here:
61f71c1#L24L34

Could you write a more detail tutorial?

1.First I don't want the screenshot immediately when the page load?

2.Second,I want when screenshot ,the screenshot will insert to another container,but now I can't get the screenshot object?

How can I prevent the default mouse click toggle event happened!?

I have two confuse:
1.how can I prevent the default mouse click toggle event happened!?which is no matter click the left or right mouse ,it toggle between the original web or the screenshot!

2.How can I get the screenshot?!it return nothing(undefined)!I want it move it to another div,not the default document,how can I get it ?

3.you API document write is very bad

Better _html2canvas.Parse separation from canvas

Hello,
first of all thank you for your great job :-) this library is really great!!

It could be very useful if you separate canvas primitives from _html2canvas.Parse so anyone could implement its own renderer.
I would be able to customize some rendering methods but I wont' change all _html2canvas.Parse code.

Thank you very much,

Bind

Changing Origin

Since this script is intended to be used for full website screen capture, it starts at the top left corner of the window. I want to use it to capture a single element on the page.

How do I change the origin point so it starts at the top left corner of the target div, rather than the window?

Tutorials & documentation

I've started up a site for the project and created some documentation. If someone wants to help out, we really could use with finishing the documentation and adding some tutorials.

If you feel like helping out, just do a pull request in the gh-pages branch.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.