使用JS将网页的元素保存为图像

我知道这个问题之前已经被问过了,但是所有的答案都是在几年前,所以也许有些改变。

我发现这个https://github.com/apollolm/phantasm ,这正是我所需要的。 但是我在OSX上,似乎不被支持。

那么,我怎样才能使用javascript来保存一个网页partulcar部分的图像?

您可以使用phantomjs来渲染页面并获取其图像。

呈现您的问题的示例:

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'); page.render("question.png"); } console.log('exiting'); phantom.exit(); }) 

phantomjs SCRIPT_FILENAME.js运行它并等待结果: 在这里输入图像说明