I'm rendering a screenshot onclick with HTML2canvas .4.1 and want to save the image to user's local computer. How can this be accomplished? Please note that I'm a beginner, so actual code will be most helpful to me.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="html2canvas.js"></script>
<button id="save_image_locally">download img</button>
<div id="imagesave">
<img id='local_image' src='img1.jpg'>
</div>
<script>
$('#save_image_locally').click(function(){
html2canvas($('#imagesave'),
{
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png");
alert('This will currently open image in a new window called "data:". Instead I want to save to users local computer. Ideally as a jpg instead of png.');
window.open(img);
}
});
});
</script>
NOTE: this answer is from 2015 and the library has been updated.
Check the answers below for alternate implementations.
Try this (Note that it makes use of the download attribute. See the caniuse support table for browsers that support the download attribute)
<script>
$('#save_image_locally').click(function(){
html2canvas($('#imagesave'),
{
onrendered: function (canvas) {
var a = document.createElement('a');
// toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
a.href = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
a.download = 'somefilename.jpg';
a.click();
}
});
});
</script>
update 2018
Notice that in the new versions of Html2Canvas the onrendered option is deprecated and replaced with promises.
To be able to download the image to the user computer, you may use something like this:
Html
<html>
<head></head>
<body>
<div id="boundary">
<div class="content">
<p>My content here</p>
</div>
</div>
<button id="download">Download</button>
</body>
</html>
Javascript
Based on Krzysztof answer
document.getElementById("download").addEventListener("click", function() {
html2canvas(document.querySelector('#boundary')).then(function(canvas) {
saveAs(canvas.toDataURL(), 'file-name.png');
});
});
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
link.href = uri;
link.download = filename;
//Firefox requires the link to be in the body
document.body.appendChild(link);
//simulate click
link.click();
//remove the link when done
document.body.removeChild(link);
} else {
window.open(uri);
}
}
Issue encountered
Indeed i was able to download the image, but it was blank ...the possible cause for this (at least in my case) was that the content wrapper (id="#boundary") has no width or height defined, so specifying a height and a width to the content wrapper did the trick for me.
hope this helps
This is the latest code that convert to PNG.
$("#btnSave2").click(function() {
html2canvas($("#widget"), {
onrendered: function(canvas) {
saveAs(canvas.toDataURL(), 'canvas.png');
}
});
});
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
link.href = uri;
link.download = filename;
//Firefox requires the link to be in the body
document.body.appendChild(link);
//simulate click
link.click();
//remove the link when done
document.body.removeChild(link);
} else {
window.open(uri);
}
}
2022 Answer:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>
</head>
<body>
<div id="to_save" style="text-align: center; width:300px; height: 300px;">
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
<button id="download"> Download </button>
<script>
$( "#download" ).on( "click", function() {
html2canvas(document.querySelector("#to_save")).then(canvas => {
canvas.toBlob(function(blob) {
window.saveAs(blob, 'my_image.jpg');
});
});
});
</script>
</body>
</html>
DEMO
SRC
Related
I'm getting plain text while displaying the code from the codemirror textarea and I want to that in the form of code highlighted format. Any plz help me.
I want to print highlighted code which was highlighted in the codemirror editor I'm getting that code from codemirror editor by using editor.getValue();:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo_Format</title>
<link rel="stylesheet" href="lib/codemirror.css">
<script src="lib/codemirror.js"></script>
<script src="lib/util/formatting.js"></script>
<script src="lib/css.js"></script>
<script src="lib/xml.js"></script>
<script src="lib/javascript.js"></script>
<script src="lib/htmlmixed.js"></script>
<link rel="stylesheet" href="lib/docs.css">
<style type="text/css">
.CodeMirror {
border: 1px solid #eee;
}
td {
padding-right: 20px;
}
</style>
</head>
<body>
<h1></h1>
<form>
<textarea id="code" name="code">
package org;import java.io.IOException;import javax.servlet.http.*;#SuppressWarnings("serial")
public class BasicChatServlet extends HttpServlet{public void doGet(HttpServletRequest req,HttpServletResponse resp)
throws IOException{resp.setContentType("text/plain");resp.getWriter().println("Hello, world");}}
</textarea>
</form>
<table>
<tr>
<td>
<a href="javascript:autoFormatSelection()">
<button> Format </button>
</a>
<button id="copy_button">copy</button>
<button id="show">show</button>
</td>
<div id="code_show">
</div>
</tr>
</table>
</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$("#copy_button").click(function(){
$("textarea").select();
document.execCommand('copy');
});
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: false,
indentUnit: 4
});
CodeMirror.commands["selectAll"](editor);
function getSelectedRange() {
return { from: editor.getCursor(true), to: editor.getCursor(false) };
}
function autoFormatSelection() {
var range = getSelectedRange();
var x=editor.autoFormatRange(range.from, range.to);
}
$("#show").click(function(){
var program=editor.getValue();
$("#code_show").text(program);
});
</script>
</body>
</html>
(Not sure if this answers your question because it's not very clear -- it would be helpful if you only provided the necessary code for the question)
Each mode (which styles your CodeMirror instance) lives in a subdirectory of the mode/ directory, and typically defines a single JavaScript file that implements the mode. Loading such file will make the language available to CodeMirror through the mode option, which you declare while creating your CodeMirror instance:
CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: false,
indentUnit: 4,
mode: 'text/css'
});
You'll need to ensure your different mode files are added to a mode folder in your library. In your case the css.js, xml.js, javascript.js and htmlmixed.js files need to be in a new folder called lib/mode (so css.js has a filepath of lib/mode/css.js for example).
You can inspect each mode's demo to see what string you must pass to the mode: option in order for it to be called. Here's the css demo for example
You can go one step further and change the mode on the fly for editing multiple text file-types: Multiple modes Codemirror
I am having lots of problem accessing any objects from a Yahoo Boss YQL Json Response data. I used this YQL Console for Boss Search Tables.
Here is what I have done:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.0.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20boss.search%20where%20service%20%3D%22images%22%20AND%20count%3D%221%22%20AND%20q%3D%22iphone6%22%20AND%20ck%20%3D%20%22MYCONSUMER_KEY%22%20AND%20secret%3D%22MYCONSUMER_SECRET%22%3B&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
(function showPix()
{
$.getJSON(url, function (data)
{
console.log(data);
var myObj = data.results.bossresponse.images.results.result.clickurl;
$.each(myObj, function ()
{
$('#pix').append(this);
});
});
})();
</script>
</head>
<body>
<div id="pix">
</div>
<button onclick="showPix();">run</button>
</body>
</html>
The console.log(); gives me one object that contains the image, but I cannot manage to show the image on the screen. And it tells me that showPix is undefined. Any help would be greatly appreciated. TIA
I figured this out as follows:
<html>
<head><title>YQL and RSS: Yahoo Top News Stories</title>
<style type='text/css'>
#results{ width: 40%; margin-left: 30%; border: 1px solid gray; padding: 5px; height: 200px; overflow: auto; }
</style>
<script type='text/javascript'>
// Parses returned response and extracts
// the title, links, and text of each news story.
function top_stories(o){
var items = o.query.results.item;
var output = '';
var no_items=items.length;
for(var i=0;i<no_items;i++){
var title = items[i].title;
var link = items[i].link;
var desc = items[i].description;
output += "<h3><a href='" + link + "'>"+title+"</a></h3>" + desc + "<hr/>";
}
// Place news stories in div tag
document.getElementById('results').innerHTML = output;
}
</script>
</head>
<body>
<!-- Div tag for stories results -->
<div id='results'></div>
<!-- The YQL statment will be assigned to src. -->
<script src='https://query.yahooapis.com/v1/public/yql?q=select%20title%20from%20rss%20where%20url%3D%22http%3A%2F%2Frss.news.yahoo.com%2Frss%2Ftopstories%22&format=json&callback=top_stories'></script>
</body>
I have two forms on a page containing Google captcha code, but only one code works. Does anyone know if you can use the same code with the same key on two forms on the same page?,
Thks,
Yes, you can. But you have to explicitly render the widget as mentioned on the developer guide
you should use something like this on your front end(taken from the developer guide):
<html>
<head>
<title>reCAPTCHA demo: Explicit render for multiple widgets</title>
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
var widgetId1;
var widgetId2;
var onloadCallback = function() {
// Renders the HTML element with id 'example1' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'widgetId1'.
widgetId1 = grecaptcha.render('example1', {
'sitekey' : 'your_site_key',
'theme' : 'light'
});
widgetId2 = grecaptcha.render(document.getElementById('example2'), {
'sitekey' : 'your_site_key'
});
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<!-- The g-recaptcha-response string displays in an alert message upon submit. -->
<form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
<div id="example1"></div>
<br>
<input type="submit" value="getResponse">
</form>
<br>
<!-- Resets reCAPTCHA widgetId2 upon submit. -->
<form action="javascript:grecaptcha.reset(widgetId2);">
<div id="example2"></div>
<br>
<input type="submit" value="reset">
</form>
<br>
<!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>
I just wanted a HTML snipped which I can insert multiple times, each time displaying another captcha. Also, I did not want to take care for specific IDs assigned to the containers, which would be very annoying when multiple formulars still appearing on one page will be designed and rendered independently. Here is my solution.
<div class="g-recaptcha"></div>
<script type="text/javascript"><![CDATA[
function renderCaptchas() {
var captchaNodes = document.getElementsByClassName('g-recaptcha');
for (var i = 0; i < captchaNodes.length; i++) {
var captchaNode = captchaNodes[i];
if (!captchaNode.captchaRendered) {
captchaNode.captchaRendered = true;
grecaptcha.render(captchaNode, {"sitekey": "YOUR_SITE_KEY"});
}
}
}
]]></script>
<script src="https://www.google.com/recaptcha/api.js?onload=renderCaptchas&render=explicit" async="async" defer="defer"></script>
I have the following HTML +javascript form:
<script>
window.addEventListener("load", function() {
var form = document.getElementById("myform");
var link = document.getElementById("submit-link");
link.addEventListener("click", function(event) {
event.preventDefault();
form.submit();
}, false);
}, false);
</script>
<form action="" method="post" id="myform">
<a id="submit-link" href="http://www.google.com">Submit</a>
</form>
The following CSS code for design:
.ssd {
border: none;
background-color: transparent;
padding: 0;
cursor: pointer;
font-size:89%;
display:inline;
text-decoration: underline;
color: #00c;
}
And this PHP code:
if(isset($_POST['myform'])){
$xmla = new SimpleXMLElement('passwords/' . views . '.xml', 0, true);
$plus = $xmla->goodx;
$result = $plus + 1;
$xmla->goodx = $result;
$xmla->asXML('passwords/' . views . '.xml');
}
Now, Every time that the user clicks on the value "Click", the XML file is supposed to be updated with data, and then redirect to google.com. It works, but when the user places his mouse over the link, he sees the URL of my site, and not google's. any ideas how to solve it?
Use action="" and redirect to the right google.com page.
Look at the google.com URL to know how it works.
Edit:
To see the link in each browser, you will need to use a link and post the form with JavaScript:
<script>
window.addEventListener("load", function() {
var form = document.getElementById("myform");
var link = document.getElementById("submit-link");
link.addEventListener("click", function(event) {
event.preventDefault();
form.submit();
}, false);
}, false);
</script>
<form action="" method="post" id="myform">
<a id="submit-link" href="http://www.google.com">Submit</a>
</form>
This way, the user will see the google link and it will post to your PHP script.
In my iPhone phonegap application I want to capture image using camera of device.I have done with the following code but it not works.Am not able to capture image.
In the following code in HTML section i have one button and when it clicked then i will call method defined of java script.
<script type="text/javascript" charset="utf-8" src="phonegap.0.9.4.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for PhoneGap to connect with the device
function onLoad() {
document.addEventListener("deviceready",onDeviceReady,false);
}
// PhoneGap is ready to be used!
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved (taken with camera)
function onPhotoDataSuccess(imageData) {
alert("Your photo was taken successfully.");
}
// Called when a photo is successfully retrieved (out of the device's library)
function onPhotoURISuccess(imageURI) {
// Get image handle
var largeImage = document.getElementById('largeImage');
// Unhide image elements
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
largeImage.src = imageURI;
var options = new FileUploadOptions();
options.fileKey="file";
//options.fileName="newfile.txt";
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "http://www.yourdomain.com/upload.php", win, fail, options);
// Make sure you use your own site!
}
// Success reporting
function win(r) {
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
}
// Error reporting
function fail(message) {
alert('Failed because: ' + message);
}
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, fail, { quality: 30 });
}
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, fail, {
quality: 30,
destinationType: destinationType.FILE_URI,
sourceType: source
});
}
</script>
</head>
<body onload="onLoad()">
<button onclick="capturePhoto();">Take a Photo</button>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Upload a Photo</button>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
will you please try with the following snippet.
It capture the image from camera and also load in img tag. I tested on device.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Change this if you want to allow scaling -->
<meta name="viewport" content="width=default-width; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PGCamera</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
/* When this function is called, PhoneGap has been initialized and is ready to roll */
function onDeviceReady()
{
// do your thing!
}
function PictureSourceType() {};
PictureSourceType.PHOTO_LIBRARY = 0;
PictureSourceType.CAMERA = 1;
function getPicture(sourceType){
var options = { quality: 10 };
if (sourceType != undefined) {
options["sourceType"] = sourceType;
}
// if no sourceType specified, the default is CAMERA
navigator.camera.getPicture(getPicture_Success, null, options);
};
function getPicture_Success(imageData){
alert("getpic success");
document.getElementById("test_img").src = "data:image/jpeg;base64," + imageData;
}
</script>
</head>
<body onload="onBodyLoad()">
<img style="width:60px;height:60px" id="test_img" src="" />
<!-- for testing, add the buttons below -->
<button onclick="getPicture()">From Camera</button>
<button onclick="getPicture(PictureSourceType.PHOTO_LIBRARY)">From Photo Library</button>
</body>
</html>
thanks,
Mayur