How to render body element in Javascript - javascript

I am using html2canvas to take a snapshot of my webpage and paste it somewhere in my server.
I am trying to Render the body element and restrict canvas size to 300x300px
This is the code that is doing to trick
html2canvas(document.body, {
onrendered: function(canvas) {
document.body.appendChild(canvas);
},
width: 300,
height: 300
});
And this is the website where the demo is available.
My problem is that I am new to html2canvas and I couldn't figure out how to paste this code and use it on my local file.
I would really appreciate it if someone can give me steps or explain for me where and how to use this code to make it screenshot my local webpage.

I'm afraid but I do not really understand what you want to do.
The above code should already take a screenshot of your webpage. You just have to include the html2canvas.js and paste the code in your main JavaScript file or your documents head.
<head>
...
<script src="js/html2canvas.js"></script>
<script>
html2canvas(document.body, {
onrendered: function(canvas) {
document.body.appendChild(canvas);
},
width: 300,
height: 300
});
</script>
</head>
Saving that image to your server is a little tricky.
HTML2Canvas renders the image via the Data URI scheme.
That means, an image file is created during the runtime and then written to the canvas (via drawImage()).
To get that data back, you may call the toDataURL() function:
html2canvas(document.body, {
onrendered: function(canvas) {
var imageData = canvas.toDataURL();
},
width:300,
height:300
});
In my case, that imageData variable contains something like data:image/png;base64,iVBORw0KGgoA....
That's an base64 encoded string of the image data with mime-type image/png.
To save that image to your server, you need something that is able to write to the server. Since JavaScript runs clientside (in your browser), it's not allowed to do so.
You could send that data to a PHP file using an AJAX call:
html2canvas(document.body, {
onrendered: function(canvas) {
var imageData = canvas.toDataURL(),
request = new XMLHTTPRequest() || new ActiveXObject("Microsoft.XMLHTTP");
request.open("POST","saveImage.php",true);
request.setRequestHeader("Content-type","image/png");
request.send("imageData=" + imageData);
},
width:300,
height:300
});
The content of that PHP file may look like the following:
<?php
if($_SERVER["REQUEST_METHOD"] !== "POST") die;
$fp = fopen("path/to/image/folder/" . time() . ".png","w");
fwrite($fp,base64_decode($_POST["imageData"]));
fclose($fp);
?>
Actually, that's the way I would do it. But the code is untested. If you have any questions, please feel free to ask!
EDIT:
Not sure if the content-type of image/png is correct or if it has to be transferred as text/plain or something like that.

Related

How to take a snapshot of webpage from the url?

I want to take a snapshot of the webpage from the url. The url is an html web page which is dynamic. Basically we needed an img of that webpage.
I thought to convert the html page to image in c# but din't work.
I first read the html using streamreader and using NReco.ImageGenerator tried to convert into bytes and finally image. This isnt working.
Finally I am trying to convert html to canvas using javascript from inside the html web page.
function report() {
let region = document.querySelector("body");
html2canvas(
$('body'),
{allowTaint: true, logging: true,'onrendered': function (canvas)
{}}).then( //getting problem here at then
function (canvas) {
let jpgUrl = canvas.toDataURL();
console.log(jpgUrl);
var text = "bottom-right Brochure1";
var imageName = text + '.jpg';
download(jpgUrl,imageName, "image/png");
}
Code explained - It will take a snpashot of the body element in the html page using js. Take the url and create the canvas from the url. and automatically download. But i face a issue ------- " html2canvas(...),then is not a function" .. I dont know why its happening. Please help.
Because of Cross-Origin Resource Sharing (CORS) restrictions in all modern browsers, this can't be done purely on the clientside. You need something on the server-side to accomplish this. To do it in javascript on the server use NodeJS there are several npm packages that can help like: node-server-screenshot, PhantomJS etc

How to get screenshot of complete HTML page using HTML2Canvas

I am using HTML2Canvas to get image of complete HTML page .I am trying to save that image in PPT on a button click.
i am able to save image in PPT.
But the saved image content is getting overlapped and the alert which i have used here is taking around 1 min to show .
when i did debug i got to know that problem is with HTML2Canvas.
i have used many third party charts in my page like Google charts.
can you please suggest me any alternative for HTML2Canvas as i saw there are few limitations in HTML2Canvas when we use cross-origin content.
$('#PPTExport').click(function(e) {
var canvas = document.getElementById('canvas');
var target = $('#loadImageHeader');
html2canvas(target, {
onrendered: function(canvas) {
var data1 = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
alert(data1);
$.ajax({
url: "savechart",
data:{
image1:data1
},
type: 'POST',
success: function (data) {
if(data=="success")
{
$("#formid1" ).attr('action','savechartDownload');
$( "#formid1" ).submit();
}
}
});
}
});
});
I Have solution for this problem.
You can try this out..
html2canvas([document.body], {
useCORS: true,
proxy: "Server",
onrendered : function(canvas) {
var myImage = canvas.toDataURL("image/png");
window.open(myImage);
}
});
Server is server url of node.js or any language you can write.
Example Node.js : https://github.com/niklasvh/html2canvas-proxy-nodejs
read more here: Can't capture google map with html2canvas
and Here: Cross-origin image load denied by Cross-Origin Resource Sharing policy

Html2canvas: facebook plugin comments

I have a website witch uses facebook plugin comments. I'm looking for a way to have those comments inside a screenshot. If I use the simple html2canvas I get a blank box instead of them. So I try to use html2canvasproxy but now it print some javascript console log instead of the facebook comments.
It shoud be like but I get . I noticed that the html2canvasproxy.php saves the facebook plugin html correctly.
I can't find any javascript error in the console log.
I'm using the following code to take the screenshot:
html2canvas(document.body, {
"logging": true, //Enable log (use Web Console for get Errors and Warnings)
"proxy":"js/html2canvasproxy.php",
"onrendered": function(canvas) {
var img = new Image();
img.onload = function() {
img.onload = null;
document.body.appendChild(img);
};
img.onerror = function() {
img.onerror = null;
if(window.console.log) {
window.console.log("Not loaded image from canvas.toDataURL");
} else {
alert("Not loaded image from canvas.toDataURL");
}
};
img.src = canvas.toDataURL("image/png");
}
});
And I have this settings in html2canvasproxy.php:
//Turn off errors because the script already own uses "error_get_last"
error_reporting(0);
//setup
define('JSLOG', 'console.log'); //Configure alternative function log, eg. console.log, alert, custom_function
define('PATH', '../screenshots');//relative folder where the images are saved
define('CCACHE', 60 * 5 * 1000);//Limit access-control and cache, define 0/false/null/-1 to not use "http header cache"
define('TIMEOUT', 30);//Timeout from load Socket
define('MAX_LOOP', 10);//Configure loop limit for redirect (location header)
define('CROSS_DOMAIN', 0);//Enable use of "data URI scheme"
//constants
define('EOL', chr(10));
define('WOL', chr(13));
define('GMDATECACHE', gmdate('D, d M Y H:i:s'));
First idea I got while reading is to include some timeout - waiting a bit longer (let's say 200ms) - so that you have more probability for things to get loaded.
But after reading this on plugin site: "The script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page." it could not help.
Personally I would investigate using another solution - like for example PhantomJS:
"PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG."
It's easy like this:
var page = require('webpage').create();
page.open('http://github.com/', function() {
page.render('github.png');
phantom.exit();
});

Angularjs - Kineticjs canvas toDataUrl not working on Chrome - images on same domain

I have been searching for a solution to this for 2 days.. the most common answer I find is "it works on the server but not on local machine".. I can verify that that is not the case. This does not work on server either...
I extracted the relevant data from a larger context to ask the question...
I manipulate kineticjs stage (canvas) and then need to save edited image to server...
I also use Angularjs and the code that sends an xhr request is this
$scope.saveStage = function (){
$scope.imageData = "";
$scope.isUser = "Tom";
stage.toDataURL({
callback: function(dataUrl) {
$scope.imageData = dataUrl;
}
});
alert("Edited Version of Your Template Will be Saved to your File Manager");
$scope.phpCtrlUrl = "saveData.php";
$scope.savedData = { imageData:$scope.imageData, isUser:$scope.isUser };
$http({
url: $scope.phpCtrlUrl,
data: $scope.savedData,
method: 'POST',
headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(data){
console.log(data);
}).error(function(err){"ERR", console.log(err)})
}
On the server side I use php to save data and image
$postdata = file_get_contents("php://input");
$data = json_decode($postdata, true);
$isUser = $data['isUser'];
$rawImageData = $data['imageData'];
// Decode image data
$filteredData = explode(',', $rawImageData);
$decodedImageData = base64_decode($filteredData[1]);
// Create the image
$imageName = "IMAGE_NAME";
$fp = fopen($imageName . '.png', 'w');
fwrite($fp, $decodedImageData);
fclose($fp);
This works really nice on Firefox but on Chrome it doesn't and it goes both for my locak machine and server..
After fiddling around a bit I realized that the behavior looks like there is a delay in the toDataURL callback.. It looks to me liek the same problem that exists around preloading images to DOM in JavaScript
stage.toDataURL({
callback: function(dataUrl) {
$scope.imageData = dataUrl;
}
});
In Firefox there is an issue if I leave out this line
alert("Edited Version of Your Template Will be Saved to your File Manager");
When I add that line the image gets created.. That is what lead me to believe that the delay created between alert and user clicking OK give the script needed time to get the canvas data.
Alert however did not change the behavior in Chrome.
Could someone help me resolve this please.
Thank you.
stage.toDataURL looks like an asynchronys call. You have a lot of possibilities solve your problem. For example put your code in the callback function.
stage.toDataURL({
callback: function(dataUrl) {
$scope.imageData = dataUrl;
$scope.phpCtrlUrl = "saveData.php";
$scope.savedData = { imageData:$scope.imageData, isUser:$scope.isUser };
$http
...
}
});
another way (I would prefer this): use promises - this is described here: http://docs.angularjs.org/api/ng.$q
Another problem is that angular is not aware of the changes in this line: $scope.imageData = dataUrl; because it is done outsite of angular. You should run your code within an $scope.$apply function:
$scope.$apply(function(){
$scope.imageData = dataUrl;
});
If you use promises angular will do this under the hood.

Take screenshot of <body> with html2canvas and store img as JS var

I am attempting to let users on my site push a button to take a screenshot of the current screen ( everything in body).
From my research, html2canvas seems to be a resource that makes this possible.
My issue is the documentation does not provide example code and I am struggling to get a grip on the steps involved.
http://html2canvas.hertzen.com/documentation.html
The following SO question ( How to upload a screenshot using html2canvas? ) leaves me a bit confused. I just want to know how to get an image at this point.
From his code.
$(window).ready(function(){
('body').html2canvas();
var canvasRecord = new html2canvas(document.body).canvas;
//At this point does the .toDataURL method return a png?
});
At this point I am lost where the image is, or even how/when to create it. Ill worry sending it to the server later.
Any information appreciated. Thanks! (html2canvas even needed?)
As you are using the html2canvas jQuery plugin, here is a sample snippet
var screenshot;
$('body').html2canvas({
onrendered: function(canvas) {
screenshot = canvas.toDataURL();
//code to process/send the image to server
}
});
In the above code snippet the html2canvas creates the screenshot of the page.
You can also use PhantomJS to create screenshots of webpages - provided that they are public pages, because you may not be able to access login protected pages on the server-side; in such situations only a client-side solution like html2canvas will work.
$("#screenshot").click(function() {
$("body").html2canvas({
onrendered: function( canvas ) {
$(".filt_opt_n").html(canvas);
//window.open(img);
}
});
});
<div id="screenshot"></div>
.filt_opt_n this is a div which u want to show the output this is working for me
May be an old question. You could try this!
var htmlCanvas = new html2canvas(document.body);
var queue = htmlCanvas.parse();
var canvas = htmlCanvas.render(queue, { elements: { length: 1} });
var img = canvas.toDataURL();

Categories

Resources