Nathan Nathan - 1 year ago 148
jQuery Question

How to take screen shot of a div with JavaScript?

I am building something called the "HTML Quiz" It's completely ran on JavaScript and it's pretty cool.

At the end, a results box pops up that says "Your Results:" and it shows how much time they took, what percentage that got and how much questions they got right out of 10. I would like to have a button that says "Capture results" and it can somehow take a screenshot or something of the div, and then it will just show the image captured on the page and they can right click and click "Save image as"

It would be so awesome if I could do this. I really would love to do this so they can share their results with others. (I don't want them to "copy" the results because they can easily change that. If they change what it says in the image, oh well.)

Does anyone know a way to do this or something similar?

Answer Source

No, I don't know of a way to 'screenshot' an element, but what you could do, is draw the quiz results into a canvas element, then use the HTMLCanvasElement object's toDataURL function to get a data: URI with the image's contents.

When the quiz is finished, do this:

var c = document.getElementById('the_canvas_element_id');
var t = c.getContext('2d');
/* then use the canvas 2D drawing functions to add text, etc. for the result */

When the user clicks "Capture", do this:'', document.getElementById('the_canvas_element_id').toDataURL());

This will open a new tab or window with the 'screenshot', allowing the user to save it. There is no way to invoke a 'save as' dialog of sorts, so this is the best you can do in my opinion.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download