yuli yuli - 4 months ago 4x
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?


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