3

I have a web app where a user can assemble a user interface (such as another webpage) out of some set of user interface components and I want to provide the option to create an image snapshot of what the user has created. In this way I want to be able to programmatically select, using JS (for example, using jQuery) a region of the browser's displayable area and create a bitmap from this region.

Thank you!

drpip
  • 63
  • 1
  • 5
  • Another [answer I posted](http://stackoverflow.com/questions/4852082/how-to-take-snap-shot-print-screen-of-client-area-and-save-as-image-in-database) may be of some help. (Since you're between a client/server-side boundary, you're going to need to store client locations and probably send them off to a server for processing. JS wont be able to capture anything from the client [for security purposes]). – Brad Christie Aug 02 '11 at 17:27
  • 1
    Don't think it's possible with straight JS, a very similar question has come up before: http://stackoverflow.com/questions/60455/take-a-screenshot-of-a-webpage-with-javascript – Griffin Aug 02 '11 at 17:29

4 Answers4

1

I managed to make this happen with taking a snapshot of the whole page with HTML2Canvas and cropping canvas to the right size.

const x = 100;
const y = 200;
const width = 200;
const height = 200;

// get the whole HTML into a canvas
html2canvas(document.querySelector('html')).then(canvas => {
    const context = canvas.getContext('2d');

    // crop the image
    context.getImageData(x, y, width, height);

    // add the copied 
    const tempCanvas = document.createElement('canvas');
    const tempContext = tempCanvas.getContext('2d');

    tempCanvas.width = width;
    tempCanvas.height = height;

    tempContext.drawImage(canvas, 0, 0);

    // load the new canvas 
    const img = tempCanvas.toDataURL('image/png');

    /*
     * ...
     * you can use the img
     * ...
     * ...
     */
});
Johnny Fekete
  • 281
  • 3
  • 5
1

Maybe this can help you: http://html2canvas.hertzen.com/

Mohsen
  • 64,437
  • 34
  • 159
  • 186
1

Straight JavaScript, unlikely.. But you don't mention your overall "setup", so it's hard to know for sure. Tools that perform aspects of what you are describing..

PhantomJS - headless WebKit with JavaScript API. Native support for DOM handling, CSS selector, JSON, Canvas, and SVG. For testing of web-based applications, site scraping, pages capture, SVG renderer, PDF converter, etc.

Zombie.js - "Insanely fast", headless full-stack testing using Node.js. Zombie.js is a lightweight framework for testing client-side JavaScript code in a simulated environment. No browser required.

webkit2png - is a command line tool that creates png screenshots of webpages.

Alex Gray
  • 16,007
  • 9
  • 96
  • 118
0

Maybe wkhtmltopdf would work, they have a 'to image' that appears to be in beta. This however requires more than just javascript to accomplish, as do other methods.