Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using PhantomJS to render web page on multiple screen sizes into animated gifs
/*
MIT License
Copyright (c) 2018 Daniel Materowski
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
console.log('running');
var page = require('webpage').create();
var gifshot = require('./gifshot.js');
var fs = require('fs');
var args = require('system').args;
if (args.length < 3) {
console.log('Url address and site alias(save folder) is required');
phantom.exit();
}
var website = args[1];
var alias = args[2] || 'render';
var gifFrameDuration = args[3] || 20; // 10 = 1 second
var gifDownScale = args[4] || 2;
var scrollingPixelStep = args[5] || 400;
var screenSizes = [
{ width: 1024, height: 768 },
{ width: 1280, height: 720 },
{ width: 1366, height: 768 },
{ width: 1600, height: 900 },
{ width: 1920, height: 1080 },
{ width: 320, height: 534 },
{ width: 375, height: 667 },
{ width: 540, height: 960 },
{ width: 720, height: 1280 },
{ width: 768, height: 1024 },
];
var finishedFiles = [];
var webserver = require('webserver');
var server = webserver.create();
var service = server.listen(8083, function (request, response) {
var path = request.url.substring(1);
console.log('request ' + path);
response.statusCode = 200;
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Content-Type', 'image/png');
response.setEncoding('binary');
var file = fs.open(path, 'rb');
var data = file.read();
file.close();
response.write(data);
response.close();
});
console.log('server started ' + service);
const GifReadyMessage = '[Injected] Gif Ready';
page.onConsoleMessage = function (msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
handlePageConsoleMessage(msg, page, continueProcessing);
};
page.onError = logError;
continueProcessing();
function continueProcessing() {
if (screenSizes.length) {
var screenSize = screenSizes.splice(0, 1)[0];
console.log(JSON.stringify(screenSize));
processSite(website, screenSize.width, screenSize.height, alias)
} else {
console.log('exiting');
console.log('produced ' + JSON.stringify(finishedFiles))
saveReport(finishedFiles, alias + '/report.html');
phantom.exit();
}
}
function processSite(url, width, height, filePrefix) {
page.open(url, function (status) {
console.log(status);
var outputFileName = filePrefix + "/" + width + "x" + height + ".gif";
console.log(outputFileName);
var files = renderPage(page, width, height, scrollingPixelStep, filePrefix);
console.log('rendered')
var injectsuccess = page.injectJs('./gifshot.js');
console.log('injecting gifshot success ' + injectsuccess)
var imagesToUse = files.map(function (f) { return 'http://localhost:8083/' + f });
console.log(imagesToUse)
page.evaluate(function (width, height, frameDuration, downscale, images, outputFileName, readyMessage) {
gifshot.createGIF({
'images': images,
'frameDuration': frameDuration,
'gifWidth': width / downscale,
'gifHeight': height / downscale,
}, function (obj) {
if (!obj.error) {
_injected_tempGifStorage = obj.image;
_injected_outputFileName = outputFileName;
console.log(readyMessage)
} else {
console.log(JSON.stringify(obj));
}
});
}, width, height, gifFrameDuration, gifDownScale, imagesToUse, outputFileName, GifReadyMessage);
});
}
function handlePageConsoleMessage(msg, page, savedCallback) {
if (msg === GifReadyMessage) {
var gif = page.evaluate(function () {
return _injected_tempGifStorage;
});
var fileName = page.evaluate(function () {
return _injected_outputFileName;
});
console.log('Saving image')
var gifContent = gif.replace(/^data:image\/gif;base64,/, '');;
fs.write(fileName, atob(gifContent), 'wb');
finishedFiles.push(fileName);
savedCallback();
}
}
function renderPage(page, width, height, scrollingStep, prefix) {
page.viewportSize = { width: width, height: height }
page.clipRect = { top: 0, left: 0, width: width, height: height };
var actualHeight = page.evaluate(function () { return document.body.scrollHeight });
var step = scrollingStep;
var stepCount = ((actualHeight - height) / step) + 1;
var files = [];
for (var i = 0; i < stepCount; i++) {
page.scrollPosition = {
top: Math.min(i * step, actualHeight - height),
left: 0
};
var fileName = "temp/" + prefix + "_" + width + "x" + height + "_" + i + ".png";
page.render(fileName);
files.push(fileName);
console.log('rendered ' + fileName);
}
return files;
}
function saveReport(files, reportFile) {
console.log('saving report to ' + reportFile)
var nodes = files.map(function (f) { return '<img style="margin:20px; border: 1px solid black; display: block;" src="../' + f + '" title="' + f + '">'; });
var content = '<html><body>' + nodes.join('\r\n') + '</body>';
fs.write(reportFile, content);
}
function logError(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function (t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.error(msgStack.join('\n'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment