yuli yuli - 1 year ago 79
Node.js Question

Saving element of webpage as an image using JS

I know that the question has been asked before, but all the answers are from a few years ago, so perhaps something changed.

I found this https://github.com/apollolm/phantasm , which seems like exactly what I need. But I'm on OSX and it appears not to be supported.

So, how can I use javascript to save an image of a partulcar portion of a webpage?

Answer Source

You can use phantomjs for rendering page and getting its image.

Example for rendering your question:

var page = require('webpage').create();

page.viewportSize = {width: 1600, height: 900};

console.log('opening page');
page.open('http://stackoverflow.com/questions/37570827/saving-element-of-webpage-as-an-image-using-js', function(status) {
    console.log('check status ', status);
    if (status == 'success') {
        console.log('getting rect for part of page which we want to render to file');
        var rect = page.evaluate(function() {
            var questionElement = document.getElementById("question");
            return questionElement.getBoundingClientRect();
        console.log('setting rect ', rect);
        page.clipRect = rect;
        console.log('rendering, check file question.png near your script');

run it with phantomjs SCRIPT_FILENAME.js and wait for result: enter image description here

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