I am very new to Protractor and Javascript/Node.js. I had a requirement where i need to take the screenshot of particular element and show the same in the jasmine report(Please note that the screenshot present in the report should not contain the entire web page, it should only contain the snap of the web element we are trying to find in the page.)
Here is the sample code which i found in stack overflow. but i couldn't take the same because it takes the screenshot of entire page.
testpage.takesnap = function(elementLocator,screenshotName){
var test1 = element(by.xpath(elementLocator)).getSize().then(function(size){
element(by.xpath(elementLocator)).getLocation().then(function(location) {
browser.takeScreenshot().then(function(data) {
var base64Data = data.replace(/^data:image\/png;base64,/, "");
fs.writeFile(screenshotFilePath+screenshotName, base64Data, 'base64', function(err) {
if (err) {
console.log(err);
}
else {
test.cropInFile(size, location, screenshotFilePath+screenshotName);
}
doneCallback();
///////////////
});
});
});
});
console.log('Completed taking screenshot');
};
testpage.cropInFile = function(size, location, filePath) {
easyimg.crop({
src: filePath,
dst: filePath,
cropwidth: size.width,
cropheight: size.height,
x: location.x,
y: location.y,
gravity: 'North-West'
},
function(err, stdout, stderr) {
if (err) throw err;
});
};
i didn't get any error but still it takes the snap of entire webpage.
I couldn't understand. I have worked in java for the same scenarios. but for the same i couldn't do it using protractor tool.
Please help me with some example.
Thanks in Advance.
Here is an example to crop the logo from a screenshot:
const fs = require('fs');
const PNG = require('pngjs').PNG;
it("should crop logo", function() {
browser.get("http://stackoverflow.com/");
var element = $("#hlogo");
protractor.promise.all([
element.getLocation(),
element.getSize(),
browser.takeScreenshot()
]).then(function(result) {
var src = PNG.sync.read(Buffer.from(result[2], 'base64'));
var dst = new PNG({width: result[1].width, height: result[1].height});
PNG.bitblt(src, dst, result[0].x, result[0].y, dst.width, dst.height, 0, 0);
fs.writeFileSync('out.png', PNG.sync.write(dst));
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With