I am trying to get the Camera API to work in my PhoneGap android app, but i keep getting this error
"Cannot read property 'getPicture' of undefined".
Now i have checked countless answers on StackOverflow and tutorials all over the web,and tried all the answer there(with no luck), and i cant seem to find the issue.
This is the button that calls the function
<button type="button" class="btn btn-primary" ng-click="getPic()">Camera</button>
This is the controller that handles the camera
myApp.controller('EditProfileCtrl', function ($scope, $http, navigateFactory) {
$scope.getPic = function () {
navigator.camera.getPicture(onSuccess, onFail, {
quality: 60,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: 1
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed beause' + message);
}
};
});
Please comment if there is any additional information required.
Any and all help will be hugely appreciated.
EDIT: So after following Aravin's advice i added <script src="cordova.js"></script>
now it atleast looks like something is happening, but now im getting these errors in my eclipse logcat:
I/System.out(3871): Error adding plugin
org.apache.cordova.CameraLauncher D/PluginManager(3871): exec() call
to unknown plugin: Camera
The total work around is below..
you need to write all code in your html page.
<body>
<div data-role="page">
<script type="text/javascript">
function getPhotoFromCamera() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 50,
sourceType: navigator.camera.PictureSourceType.CAMERA,
destinationType: navigator.camera.DestinationType.DATA_URL,
});
}
function onPhotoDataSuccess(imageData){
var image = document.getElementById('image');
image.style.display = 'block';
image.src = "data:image/jpeg;base64,"+imageData;
}
function getPhotoFromAlbum(){
navigator.camera.getPicture(onPhotoURISuccess, onFail,{
quality: 50,
sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM,
destinationType: navigator.camera.DestinationType.FILE_URI
});
}
function onPhotoURISuccess(imageURI){
var image = document.getElementById('image');
image.style.display = 'block';
image.src = imageURI;
}
function onFail(message){
alert('Failed because:' + message);
}
</script>
<div data-role="header" style="height:36px;">
<h1>Write New</h1>
Back
</div>
<button onclick="getPhotoFromCamera();">Launch Camera</button>
<button onclick="getPhotoFromAlbum();">Goto Picture Gallery</button>
<div>
<img id="image" style="display:none;width;290px;height:210px;" src = ""/>
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
</body>
If you are using TFS, remember to check out for edit "fetch.json" before installing the plugin, or it will fail mid-installation.
So after trying all the things here with no success I did this which fixed the issue (dont know how)...
remove the plugin , build , add the plugin , build
and Magic!
Related
I came across jsNode library here Generate pdf from HTML in div using Javascript
So I've installed. I'm tryna use it to print a leaflet map. It seems I was not able to set it propely. It create the PDF but nothing shows on the map. Could you help me with that ?
Javascript
function genPDF() {
var doc = new jsPDF();
var elementHandler = {
'#ignorePDF': function(element, renderer) {
return true;
}
};
var source = window.document.getElementsByTagName("div")[0];
doc.fromHTML(
source,
15,
15, {
'width': 180,
'elementHandlers': elementHandler
});
doc.output("dataurlnewwindow");
}
HTML
<html>
<body onload="Create_MAP();">
<div id="map">
</div>
<input type="button" class="bt" value="PRINT PDF" onclick="genPDF();">
</body>
</html>
You need to turn your leaflet map into an image first.
You can use https://github.com/mapbox/leaflet-image
Then add that image to jsPDF for export.
I am using ionic framework, I want to pick a image file from galley and want to convert it to PDF and want to save it on filesystem on phone.
Is there any javascript or cordova plugin is available to perform this task.
I found jsPDF can be use to convert image to pdf but, does it really work on mobile?
I hope I'm not that late!
Aside from jSPDF, following packages are needed:
cordova-plugin-file
cordova-plugin-file-opener2
And install the corresponding ionic-package:
bower install ngCordova
Please note that, there are several possible solution as to how to save a pdf file in your filesystem. I had to move the pdf-file to a certain directory in order to open it. Nevertheless this solution works on all android phones I've tested so far and you can create all pdfs you like.
iOS: You might modify the storage-directory so that it works on iOS-Version as well.
Index.html:
<head>
<meta charset="utf-8">
... include jsPDF
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>
....
some html
....
... include ngCordova
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
.... the core-library
<script src="cordova.js"></script>
....
</head>
View.html:
<ion-view view-title="Dashboard">
<ion-content class="padding">
<p on-tap="savePDF()">Create PDF</p>
<p on-tap="openPDF()">Open PDF</p>
</ion-content>
</ion-view>
App-JS:
// to not forget to include ngCordova in order to use $cordovaFile in your controller
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','ngCordova'])
...
...
Controller-JS:
angular.module('starter.controllers', []).controller('DashCtrl', function($scope,$cordovaFile) {
$scope.pdfFilename = "test.pdf";
$scope.makePDF = function(){
var imgData = "your base64 image-data";
var doc = new jsPDF();
doc.setFontSize(40);
doc.text(35, 25, "Octonyan loves jsPDF");
doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);
return doc.output('blob');
};
$scope.getDirectoryInfo = function(){
return {
storage: cordova.file.externalRootDirectory, // for android, you may have to use another directory
pdfDir: cordova.file.externalRootDirectory+"pdfs/"
}
};
$scope.savePDF = function(){
var dirs = $scope.getDirectoryInfo();
var storageDir = dirs.storage;
// create directory on the first place if it has not been created so far
$cordovaFile.createDir(storageDir, "pdfs", false);
var pdfBlob = $scope.makePDF();
// create empty pdf-file(in the root-dir)
$cordovaFile.createFile(storageDir, $scope.pdfFilename, true).then(function(success) {
// write pdf-file(in the root dir)
$cordovaFile.writeExistingFile(storageDir, $scope.pdfFilename, pdfBlob, true).then(function (success) {
var fullTmpPath = storageDir + $scope.pdfFilename;
window.resolveLocalFileSystemURL(fullTmpPath, function (fileEntry) {
// get destination-directory to put your pdf into
window.resolveLocalFileSystemURL(dirs.pdfDir, function (dirEntry) {
// move written pdf to the destination-directory
fileEntry.moveTo(dirEntry, $scope.pdfFilename, function (newFileEntry) {
alert($scope.pdfFilename+' is finish! Now you can open it');
});
});
});
}, function (error) {
console.log('there was some error while writting file: ',error);
});
});
};
$scope.openPDF =function(){
var dirs = $scope.getDirectoryInfo();
cordova.plugins.fileOpener2.open(dirs.pdfDir+$scope.pdfFilename,'application/pdf',function(){
console.log('success');
});
};
});
Hope this helps despite the fact that your question has been put some time ago.
I am building something called the "HTML Quiz". It's completely ran on JavaScript and it's pretty cool.
At the end, a results box pops up that says "Your Results:" and it shows how much time they took, what percentage they got, and how many questions they got right out of 10. I would like to have a button that says "Capture results" and have it somehow take a screenshot or something of the div, and then just show the image captured on the page where they can right click and "Save image as."
I really would love to do this so they can share their results with others. I don't want them to "copy" the results because they can easily change that. If they change what it says in the image, oh well.
Does anyone know a way to do this or something similar?
No, I don't know of a way to 'screenshot' an element, but what you could do, is draw the quiz results into a canvas element, then use the HTMLCanvasElement object's toDataURL function to get a data: URI with the image's contents.
When the quiz is finished, do this:
var c = document.getElementById('the_canvas_element_id');
var t = c.getContext('2d');
/* then use the canvas 2D drawing functions to add text, etc. for the result */
When the user clicks "Capture", do this:
window.open('', document.getElementById('the_canvas_element_id').toDataURL());
This will open a new tab or window with the 'screenshot', allowing the user to save it. There is no way to invoke a 'save as' dialog of sorts, so this is the best you can do in my opinion.
This is an expansion of #Dathan's answer, using html2canvas and FileSaver.js.
$(function() {
$("#btnSave").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
theCanvas = canvas;
canvas.toBlob(function(blob) {
saveAs(blob, "Dashboard.png");
});
}
});
});
});
This code block waits for the button with the id btnSave to be clicked. When it is, it converts the widget div to a canvas element and then uses the saveAs() FileSaver interface (via FileSaver.js in browsers that don't support it natively) to save the div as an image named "Dashboard.png".
An example of this working is available at this fiddle.
After hours of research, I finally found a solution to take a screenshot of an element, even if the origin-clean FLAG is set (to prevent XSS), that´s why you can even capture for example Google Maps (in my case). I wrote a universal function to get a screenshot. The only thing you need in addition is the html2canvas library (https://html2canvas.hertzen.com/).
Example:
getScreenshotOfElement($("div#toBeCaptured").get(0), 0, 0, 100, 100, function(data) {
// in the data variable there is the base64 image
// exmaple for displaying the image in an <img>
$("img#captured").attr("src", "data:image/png;base64,"+data);
});
Keep in mind console.log() and alert() won´t generate output if the size of the image is great.
Function:
function getScreenshotOfElement(element, posX, posY, width, height, callback) {
html2canvas(element, {
onrendered: function (canvas) {
var context = canvas.getContext('2d');
var imageData = context.getImageData(posX, posY, width, height).data;
var outputCanvas = document.createElement('canvas');
var outputContext = outputCanvas.getContext('2d');
outputCanvas.width = width;
outputCanvas.height = height;
var idata = outputContext.createImageData(width, height);
idata.data.set(imageData);
outputContext.putImageData(idata, 0, 0);
callback(outputCanvas.toDataURL().replace("data:image/png;base64,", ""));
},
width: width,
height: height,
useCORS: true,
taintTest: false,
allowTaint: false
});
}
If you wish to have "Save as" dialog, just pass image into php script, which adds appropriate headers
Example "all-in-one" script script.php
<?php if(isset($_GET['image'])):
$image = $_GET['image'];
if(preg_match('#^data:image/(.*);base64,(.*)$#s', $image, $match)){
$base64 = $match[2];
$imageBody = base64_decode($base64);
$imageFormat = $match[1];
header('Content-type: application/octet-stream');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); // required for certain browsers
header("Content-Disposition: attachment; filename=\"file.".$imageFormat."\";" ); //png is default for toDataURL
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".strlen($imageBody));
echo $imageBody;
}
exit();
endif;?>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js?ver=1.7.2'></script>
<canvas id="canvas" width="300" height="150"></canvas>
<button id="btn">Save</button>
<script>
$(document).ready(function(){
var canvas = document.getElementById('canvas');
var oCtx = canvas.getContext("2d");
oCtx.beginPath();
oCtx.moveTo(0,0);
oCtx.lineTo(300,150);
oCtx.stroke();
$('#btn').on('click', function(){
// opens dialog but location doesnt change due to SaveAs Dialog
document.location.href = '/script.php?image=' + canvas.toDataURL();
});
});
</script>
Add this Script in your index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
Use this function to get screenshot of div tag
getScreenShot(){
let c = this.elem.nativeElement.querySelector('.chartContainer'); // or document.getElementById('canvas');
html2canvas(c).then((canvas:any)=>{
var t = canvas.toDataURL().replace("data:image/png;base64,", "");
this.downloadBase64File('image/png',t,'image');
})
}
downloadBase64File(contentType:any, base64Data:any, fileName:any) {
const linkSource = `data:${contentType};base64,${base64Data}`;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
You can't take a screen-shot: it would be an irresponsible security risk to let you do so. However, you can:
Do things server-side and generate an image
Draw something similar to a Canvas and render that to an image (in a browser that supports it)
Use some other drawing library to draw directly to the image (slow, but would work on any browser)
var shot1=imagify($('#widget')[0], (base64) => {
$('img.screenshot').attr('src', base64);
});
Take a look at htmlshot package , then, check deeply the client side section:
npm install htmlshot
<script src="/assets/backend/js/html2canvas.min.js"></script>
<script>
$("#download").on('click', function(){
html2canvas($("#printform"), {
onrendered: function (canvas) {
var url = canvas.toDataURL();
var triggerDownload = $("<a>").attr("href", url).attr("download", getNowFormatDate()+"电子签名详细信息.jpeg").appendTo("body");
triggerDownload[0].click();
triggerDownload.remove();
}
});
})
</script>
quotation
It's to simple you can use this code for capture the screenshot of particular area
you have to define the div id in html2canvas. I'm using here 2 div-:
div id="car"
div id ="chartContainer"
if you want to capture only cars then use car i'm capture here car only you can change chartContainer for capture the graph
html2canvas($('#car')
copy and paste this code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title:{
text: "Simple Line Chart"
},
axisY:{
includeZero: false
},
data: [{
type: "line",
dataPoints: [
{ y: 450 },
{ y: 414},
{ y: 520, indexLabel: "highest",markerColor: "red", markerType: "triangle" },
{ y: 460 },
{ y: 450 },
{ y: 500 },
{ y: 480 },
{ y: 480 },
{ y: 410 , indexLabel: "lowest",markerColor: "DarkSlateGrey", markerType: "cross" },
{ y: 500 },
{ y: 480 },
{ y: 510 }
]
}]
});
chart.render();
}
</script>
</head>
<body bgcolor="black">
<div id="wholebody">
<button style="background:aqua; cursor:pointer">Get Screenshot of Cars onl </button>
<div id="car" align="center">
<i class="fa fa-car" style="font-size:70px;color:red;"></i>
<i class="fa fa-car" style="font-size:60px;color:red;"></i>
<i class="fa fa-car" style="font-size:50px;color:red;"></i>
<i class="fa fa-car" style="font-size:20px;color:red;"></i>
<i class="fa fa-car" style="font-size:50px;color:red;"></i>
<i class="fa fa-car" style="font-size:60px;color:red;"></i>
<i class="fa fa-car" style="font-size:70px;color:red;"></i>
</div>
<br>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="box1">
</div>
</div>>
</body>
<script>
function genScreenshotgraph()
{
html2canvas($('#car'), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL("image/jpeg");
var pdf = new jsPDF();
pdf.addImage(imgData, 'JPEG', 0, 0, -180, -180);
pdf.save("download.pdf");
}
});
}
</script>
</html>
As far as I know you can't do that, I may be wrong. However I'd do this with php, generate a JPEG using php standard functions and then display the image, should not be a very hard job, however depends on how flashy the contents of the DIV are
Add to your html file and id="capture" to the div you want to take screenshot
<a id="btn-Convert-Html2Image" href="#">Download</a>
<script src="capture.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js" type="text/javascript"></script>
In capture.js add:
document.getElementById("btn-Convert-Html2Image").addEventListener("click", function() {
html2canvas(document.getElementById("capture")).then(function (canvas) {
var anchorTag = document.createElement("a");
anchorTag.download = "filename.jpg";
anchorTag.href = canvas.toDataURL();
anchorTag.target = '_blank';
anchorTag.click();
});
});
Then, just press download and it will download the screenshot
Or you can view screenshot img by add
<div id="previewImg"></div>
in html code is where you want to view that img and js code will be
document.getElementById("btn-Convert-Html2Image").addEventListener("click", function() {
html2canvas(document.getElementById("capture")).then(function (canvas) {
var anchorTag = document.createElement("a");
document.body.appendChild(anchorTag);
document.getElementById("previewImg").appendChild(canvas);
anchorTag.click();
});
});
This is an ~11 year old answer. Please ignore this answer and check other recent answers here
As far as I know its not possible with javascript.
What you can do for every result create a screenshot, save it somewhere and point the user when clicked on save result. (I guess no of result is only 10 so not a big deal to create 10 jpeg image of results)
I'm developing an app that will capture and save a photo library on ipad, I am using the api library will phonegap camera, and I'm having trouble because the code is not returning any errors so I can know what is happening can someone help me This is my code
<!DOCTYPE html>
<html>
<head>
<title>Capture Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64-encoded image data
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
//
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
<button onclick="capturePhoto();">Capture Photo</button> <br>
<button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
You have to explicitly add plugin via terminal (command line terminal) then your mention code will be working.
$ phonegap local plugin add org.apache.cordova.camera
$ phonegap local plugin add org.apache.cordova.media-capture
have you done this?
I am building something called the "HTML Quiz". It's completely ran on JavaScript and it's pretty cool.
At the end, a results box pops up that says "Your Results:" and it shows how much time they took, what percentage they got, and how many questions they got right out of 10. I would like to have a button that says "Capture results" and have it somehow take a screenshot or something of the div, and then just show the image captured on the page where they can right click and "Save image as."
I really would love to do this so they can share their results with others. I don't want them to "copy" the results because they can easily change that. If they change what it says in the image, oh well.
Does anyone know a way to do this or something similar?
No, I don't know of a way to 'screenshot' an element, but what you could do, is draw the quiz results into a canvas element, then use the HTMLCanvasElement object's toDataURL function to get a data: URI with the image's contents.
When the quiz is finished, do this:
var c = document.getElementById('the_canvas_element_id');
var t = c.getContext('2d');
/* then use the canvas 2D drawing functions to add text, etc. for the result */
When the user clicks "Capture", do this:
window.open('', document.getElementById('the_canvas_element_id').toDataURL());
This will open a new tab or window with the 'screenshot', allowing the user to save it. There is no way to invoke a 'save as' dialog of sorts, so this is the best you can do in my opinion.
This is an expansion of #Dathan's answer, using html2canvas and FileSaver.js.
$(function() {
$("#btnSave").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
theCanvas = canvas;
canvas.toBlob(function(blob) {
saveAs(blob, "Dashboard.png");
});
}
});
});
});
This code block waits for the button with the id btnSave to be clicked. When it is, it converts the widget div to a canvas element and then uses the saveAs() FileSaver interface (via FileSaver.js in browsers that don't support it natively) to save the div as an image named "Dashboard.png".
An example of this working is available at this fiddle.
After hours of research, I finally found a solution to take a screenshot of an element, even if the origin-clean FLAG is set (to prevent XSS), that´s why you can even capture for example Google Maps (in my case). I wrote a universal function to get a screenshot. The only thing you need in addition is the html2canvas library (https://html2canvas.hertzen.com/).
Example:
getScreenshotOfElement($("div#toBeCaptured").get(0), 0, 0, 100, 100, function(data) {
// in the data variable there is the base64 image
// exmaple for displaying the image in an <img>
$("img#captured").attr("src", "data:image/png;base64,"+data);
});
Keep in mind console.log() and alert() won´t generate output if the size of the image is great.
Function:
function getScreenshotOfElement(element, posX, posY, width, height, callback) {
html2canvas(element, {
onrendered: function (canvas) {
var context = canvas.getContext('2d');
var imageData = context.getImageData(posX, posY, width, height).data;
var outputCanvas = document.createElement('canvas');
var outputContext = outputCanvas.getContext('2d');
outputCanvas.width = width;
outputCanvas.height = height;
var idata = outputContext.createImageData(width, height);
idata.data.set(imageData);
outputContext.putImageData(idata, 0, 0);
callback(outputCanvas.toDataURL().replace("data:image/png;base64,", ""));
},
width: width,
height: height,
useCORS: true,
taintTest: false,
allowTaint: false
});
}
If you wish to have "Save as" dialog, just pass image into php script, which adds appropriate headers
Example "all-in-one" script script.php
<?php if(isset($_GET['image'])):
$image = $_GET['image'];
if(preg_match('#^data:image/(.*);base64,(.*)$#s', $image, $match)){
$base64 = $match[2];
$imageBody = base64_decode($base64);
$imageFormat = $match[1];
header('Content-type: application/octet-stream');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); // required for certain browsers
header("Content-Disposition: attachment; filename=\"file.".$imageFormat."\";" ); //png is default for toDataURL
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".strlen($imageBody));
echo $imageBody;
}
exit();
endif;?>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js?ver=1.7.2'></script>
<canvas id="canvas" width="300" height="150"></canvas>
<button id="btn">Save</button>
<script>
$(document).ready(function(){
var canvas = document.getElementById('canvas');
var oCtx = canvas.getContext("2d");
oCtx.beginPath();
oCtx.moveTo(0,0);
oCtx.lineTo(300,150);
oCtx.stroke();
$('#btn').on('click', function(){
// opens dialog but location doesnt change due to SaveAs Dialog
document.location.href = '/script.php?image=' + canvas.toDataURL();
});
});
</script>
Add this Script in your index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
Use this function to get screenshot of div tag
getScreenShot(){
let c = this.elem.nativeElement.querySelector('.chartContainer'); // or document.getElementById('canvas');
html2canvas(c).then((canvas:any)=>{
var t = canvas.toDataURL().replace("data:image/png;base64,", "");
this.downloadBase64File('image/png',t,'image');
})
}
downloadBase64File(contentType:any, base64Data:any, fileName:any) {
const linkSource = `data:${contentType};base64,${base64Data}`;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
You can't take a screen-shot: it would be an irresponsible security risk to let you do so. However, you can:
Do things server-side and generate an image
Draw something similar to a Canvas and render that to an image (in a browser that supports it)
Use some other drawing library to draw directly to the image (slow, but would work on any browser)
var shot1=imagify($('#widget')[0], (base64) => {
$('img.screenshot').attr('src', base64);
});
Take a look at htmlshot package , then, check deeply the client side section:
npm install htmlshot
<script src="/assets/backend/js/html2canvas.min.js"></script>
<script>
$("#download").on('click', function(){
html2canvas($("#printform"), {
onrendered: function (canvas) {
var url = canvas.toDataURL();
var triggerDownload = $("<a>").attr("href", url).attr("download", getNowFormatDate()+"电子签名详细信息.jpeg").appendTo("body");
triggerDownload[0].click();
triggerDownload.remove();
}
});
})
</script>
quotation
It's to simple you can use this code for capture the screenshot of particular area
you have to define the div id in html2canvas. I'm using here 2 div-:
div id="car"
div id ="chartContainer"
if you want to capture only cars then use car i'm capture here car only you can change chartContainer for capture the graph
html2canvas($('#car')
copy and paste this code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title:{
text: "Simple Line Chart"
},
axisY:{
includeZero: false
},
data: [{
type: "line",
dataPoints: [
{ y: 450 },
{ y: 414},
{ y: 520, indexLabel: "highest",markerColor: "red", markerType: "triangle" },
{ y: 460 },
{ y: 450 },
{ y: 500 },
{ y: 480 },
{ y: 480 },
{ y: 410 , indexLabel: "lowest",markerColor: "DarkSlateGrey", markerType: "cross" },
{ y: 500 },
{ y: 480 },
{ y: 510 }
]
}]
});
chart.render();
}
</script>
</head>
<body bgcolor="black">
<div id="wholebody">
<button style="background:aqua; cursor:pointer">Get Screenshot of Cars onl </button>
<div id="car" align="center">
<i class="fa fa-car" style="font-size:70px;color:red;"></i>
<i class="fa fa-car" style="font-size:60px;color:red;"></i>
<i class="fa fa-car" style="font-size:50px;color:red;"></i>
<i class="fa fa-car" style="font-size:20px;color:red;"></i>
<i class="fa fa-car" style="font-size:50px;color:red;"></i>
<i class="fa fa-car" style="font-size:60px;color:red;"></i>
<i class="fa fa-car" style="font-size:70px;color:red;"></i>
</div>
<br>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="box1">
</div>
</div>>
</body>
<script>
function genScreenshotgraph()
{
html2canvas($('#car'), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL("image/jpeg");
var pdf = new jsPDF();
pdf.addImage(imgData, 'JPEG', 0, 0, -180, -180);
pdf.save("download.pdf");
}
});
}
</script>
</html>
As far as I know you can't do that, I may be wrong. However I'd do this with php, generate a JPEG using php standard functions and then display the image, should not be a very hard job, however depends on how flashy the contents of the DIV are
Add to your html file and id="capture" to the div you want to take screenshot
<a id="btn-Convert-Html2Image" href="#">Download</a>
<script src="capture.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js" type="text/javascript"></script>
In capture.js add:
document.getElementById("btn-Convert-Html2Image").addEventListener("click", function() {
html2canvas(document.getElementById("capture")).then(function (canvas) {
var anchorTag = document.createElement("a");
anchorTag.download = "filename.jpg";
anchorTag.href = canvas.toDataURL();
anchorTag.target = '_blank';
anchorTag.click();
});
});
Then, just press download and it will download the screenshot
Or you can view screenshot img by add
<div id="previewImg"></div>
in html code is where you want to view that img and js code will be
document.getElementById("btn-Convert-Html2Image").addEventListener("click", function() {
html2canvas(document.getElementById("capture")).then(function (canvas) {
var anchorTag = document.createElement("a");
document.body.appendChild(anchorTag);
document.getElementById("previewImg").appendChild(canvas);
anchorTag.click();
});
});
This is an ~11 year old answer. Please ignore this answer and check other recent answers here
As far as I know its not possible with javascript.
What you can do for every result create a screenshot, save it somewhere and point the user when clicked on save result. (I guess no of result is only 10 so not a big deal to create 10 jpeg image of results)