Создавайте совершенные изображения скриншотов сайтов, используя следующие функции GrabzIt's Node.js API, Однако, прежде чем начать, помните, что после вызова url_to_image, html_to_image or file_to_image методы save or save_to метод должен быть вызван, чтобы сделать снимок экрана.
Требуется только один параметр, чтобы сделать снимок экрана веб-страницы или конвертировать HTML intизображение как показано в следующем примере.
client.url_to_image("https://www.tesla.com"); //Then call the save or save_to method
client.html_to_image("<html><body><h1>Hello World!</h1></body></html>"); //Then call the save or save_to method
client.file_to_image("example.html"); //Then call the save or save_to method
API GrabzIt Node.js может делать снимки экрана в нескольких форматах, включая JPG, PNG, WEBP, BMP (бит 8, бит 16, бит 24 или бит 32) и TIFF. Формат по умолчанию для снимков экрана - JPG. Однако качество изображения JPG может быть недостаточно хорошим для некоторых приложений в этих условиях. Формат PNG рекомендуется для снимков экрана, поскольку он обеспечивает хороший баланс между качеством и размером файла. В приведенном ниже примере показан снимок экрана, снятый в формате PNG.
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"format":"png"}; client.url_to_image("https://www.tesla.com", options); //Then call the save or save_to method client.save_to("result.png", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"format":"png"}; client.html_to_image("<html><body><h1>Hello World!</h1></body></html>", options); //Then call the save or save_to method client.save_to("result.png", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"format":"png"}; client.file_to_image("example.html", options); //Then call the save or save_to method client.save_to("result.png", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
Размер браузера относится к размеру окна браузера, которое будет использоваться при захвате скриншота, в большинстве случаев его не нужно устанавливать, так как размер браузера по умолчанию будет достаточным для всех большинства задач. Однако, если вы хотите установить ширину и высоту браузера, пример показан ниже.
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"browserWidth":1366, "browserHeight":768}; client.url_to_image("https://www.tesla.com", options); //Then call the save or save_to method client.save_to("result.jpg", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"browserWidth":1366, "browserHeight":768}; client.html_to_image("<html><body><h1>Hello World!</h1></body></html>", options); //Then call the save or save_to method client.save_to("result.jpg", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"browserWidth":1366, "browserHeight":768}; client.file_to_image("example.html", options); //Then call the save or save_to method client.save_to("result.jpg", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
Изменить размер изображения легко, сделать это без искажения изображения немного сложнее. Чтобы упростить весь процесс, мы рекомендуем использовать это простой калькулятор размеров изображения.
Если вы хотите увеличить ширину и высоту изображения до размера, превышающего ширину и высоту браузера, которые по умолчанию равны 1366 на 728 пикселей, ширина и высота браузера также должны быть увеличены для соответствия.
Вы можете передать пользовательский идентификатор изображение методами, как показано ниже, это значение затем возвращается в ваш обработчик GrabzIt Node.js. Например, этот пользовательский идентификатор может быть идентификатором базы данных, что позволяет связать снимок экрана с определенной записью базы данных.
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"customId":123456}; client.url_to_image("https://www.tesla.com", options); //Then call the save method client.save("http://www.example.com/handler", function (error, id){ if (error != null){ throw error; } });
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"customId":123456}; client.html_to_image("<html><body><h1>Hello World!</h1></body></html>", options); //Then call the save method client.save("http://www.example.com/handler", function (error, id){ if (error != null){ throw error; } });
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"customId":123456}; client.file_to_image("example.html", options); //Then call the save method client.save("http://www.example.com/handler", function (error, id){ if (error != null){ throw error; } });
GrabzIt позволяет вам сделать полный снимок экрана всей веб-страницы, для этого вам нужно передать -1 в browserHeight
свойство. Чтобы изображение соответствовало размеру браузера, передайте -1 height
и width
свойства.
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"browserHeight":-1,"width":-1, "height":-1}; client.url_to_image("https://www.tesla.com", options); //Then call the save or save_to method client.save_to("result.jpg", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"browserHeight":-1,"width":-1, "height":-1}; client.html_to_image("<html><body><h1>Hello World!</h1></body></html>", options); //Then call the save or save_to method client.save_to("result.jpg", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"browserHeight":-1,"width":-1, "height":-1}; client.file_to_image("example.html", options); //Then call the save or save_to method client.save_to("result.jpg", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
Вы также можете вернуть миниатюры, которые не обрезаны, но будьте осторожны, это может создать большие изображения. Для этого передайте -1 height
и / или width
свойства. Измерение, переданное как -1, не будет обрезано.
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"width":-1, "height":-1}; client.url_to_image("https://www.tesla.com", options); //Then call the save or save_to method client.save_to("result.jpg", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"width":-1, "height":-1}; client.html_to_image("<html><body><h1>Hello World!</h1></body></html>", options); //Then call the save or save_to method client.save_to("result.jpg", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); var options = {"width":-1, "height":-1}; client.file_to_image("example.html", options); //Then call the save or save_to method client.save_to("result.jpg", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
Использование этих специальных значений означает, что вы можете создать снимок экрана, представляющий собой полноразмерную версию всей веб-страницы, если хотите!
GrabzIt позволяет сделать снимок экрана с HTML-элемента, такого как div
or span
тег и захватить весь его контент. Для этого необходимо указать HTML-элемент, который вы хотите сделать на снимке экрана, как CSS селектор.
... <div id="features"> <img src="http://www.example.com/boat.jpg"/><h3>New Boat Launched</h3> </div> ...
В приведенном ниже примере мы выберем div с идентификатором «features» и выведем его в виде изображения JPEG 250 x 250px.
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); // The 250 parameters indicates that image should be sized to 250 x 250 px var options = {"width":250, "height":250, "format":"jpg","target":"#features"}; client.url_to_image("http://www.bbc.co.uk/news", options); //Then call the save or save_to method client.save_to("result.jpg", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });
В следующем примере делается еще один снимок экрана с разделом «features», но на этот раз выводится изображение JPEG, которое является точным размером элемента Div.
var grabzit = require('grabzit'); var client = new grabzit("Sign in to view your Application Key", "Sign in to view your Application Secret"); // The minus ones indicates that image should not be cropped var options = {"browserHeight":-1, "width":-1, "height":-1, "format":"jpg", "target":"#features"}; client.url_to_image("http://www.bbc.co.uk/news", options); //Then call the save or save_to method client.save_to("result.jpg", function (error, id){ //this callback is called once the capture is downloaded if (error != null){ throw error; } });