Recently I've been attempting to create a photo booth by relying on Webrtc and have nearly completed all of the code except I've not been able to figure out a way to save the image after it has been captured.
This is the closest I've come so far to achieving my goal:
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>fotogoof</title>
<link rel="Stylesheet" href="css/bootstrap.css"/>
<link rel="Stylesheet" href="css/style.css"/>
<script type="text/javascript">
window.onload = function () {
var img = document.getElementById('screenshot');
var button = document.getElementById('saveImage');
img.src = '';
img.onload = function () {
button.removeAttribute('disabled');
};
button.onclick = function () {
window.location.href = img.src.replace('image/png', 'image/octet-stream');
};
};
</script>
</head>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<h2 class="brand">Html5 Photobooth</h1>
</div>
</div>
</div>
<div class="container" id="body-wrap">
<div class="container" id="main">
<div class="span10">
<div id="video-container">
<canvas width="400" height="320" class="mask"></canvas>
<div id="counter">
</div>
</div>
<br><div id="pic-holder" class="pull-left"><img id="screenshot"></div></br>
<input id="saveImage" type="button" value="save image" disabled="disabled"/>
</div>
</div>
</div>
</div>
The code is essentially taking the webcam stream and feeding it into a canvas element. Pressing the space button triggers a screenshot to be taken, which then appears as an image. Because I'm unable to provide the exact source of the file that is being downloaded the button only opens the image in another tab in the browser instead of functioning properly. I would really appreciate some input as to how I can resolve this. Thanks in advance.
I've already managed to do capture the stream from the canvas in an image with this bit of code:
document.addEventListener ('keydown', function (event) {
if(event.keyCode == 32) {
document.querySelector('#screenshot').src = canvas.toDataURL('image/webp')
}
})
What I want to know is how to enable the user to save the image onto their computer from there.
If I understand correctly you want to download (ie. provide a save dialog for the user to pick a location) the image to user's machine?'
If so you can use this snippet:
function download(canvas, filename) {
/// create an "off-screen" anchor tag
var lnk = document.createElement('a'),
e;
/// the key here is to set the download attribute of the a tag
lnk.download = filename;
/// convert canvas content to data-uri for link. When download
/// attribute is set the content pointed to by link will be
/// pushed as "download" in HTML5 capable browsers
lnk.href = c.toDataURL();
/// create a "fake" click-event to trigger the download
if (document.createEvent) {
e = document.createEvent("MouseEvents");
e.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false,
false, 0, null);
lnk.dispatchEvent(e);
} else if (lnk.fireEvent) {
lnk.fireEvent("onclick");
}
}
Now all you need to do is to provide a default file name and call the function:
download(myCanvas, 'untitled.png');
If you rather than this mean save directly to user's harddisk then you can't due to security reasons.
That being said, there is always the option of using local storage such as File API or Indexed DB - but as these are sand-boxed you and the user will only have access to the "files" through the browser so perhaps not so convenient.
I don't think it's possible for IE without involving a server side script. Here's a good writeup on how to do it that way.
I had this problem and this is the best solution without any external or additional script libraries:
In Javascript tags or file create this function:
We assume here that canvas is your canvas:
function download(){
var download = document.getElementById("download");
var image = document.getElementById("canvas").toDataURL("image/png")
.replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
}
In the body part of your HTML specify the button:
<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>
This is working and download link looks like a button.
Regarding the first task, you can export the canvas content to an image with toDataUrl method supported by the canvas object.
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d"); // Get the context for the canvas.
var myImage = canvas.toDataURL("image/png"); // Get the data as an image.
}
var image = document.getElementById("screenshot"); // Get the image object.
image.src = myImage;
Related
I have a canvas which shows a graph and I'm trying to take a screenshot of the canvas using html2canvas() with the code below :
<div class="chartContainer" id="chart1"></div>
<div id="displayCanvas" style="display:none;" class="stx-dialog"></div>
html2canvas($('#chart1'),{onrendered:function(canvas1)
{$('#displayCanvas').append(canvas1)}});
Here when the chart container is loaded the it uses the div with the id "displayCanvas" and appends the screenshot of the canvas.
How can I download the screenshot of the canvas which is displayed?
I have already tried using something like below to download the image:
var link = document.createElement('a');
link.download = stx.chart.symbol+".png";
link.href = stx.chart.canvas.toDataURL("png");
link.click();
but it only downloads the data on the canvas as an image without the background (it does not download the screenshot but only the data) which when opened after downloading shows a black screen with data in it. Can anyone help me on how to download the image directly of the screenshot taken from the html2Canvas()?
TRY THIS:
In the HTML:
Give the element that you want to screenshot, an ID of "capture".
Give the button/element that you would need to click to take the screenshot, an ID of "btn".
Load the html2canvas.min.js file.
In the Javascript:
Create the capture() function.
Bind the capture() function to whatever event you are using—in this case it's on the btn click event.
DONE! Watch the magic happen when you click on the btn.
HTML:
<h1 id="capture">Hellooooo</h1>
<button id="btn">Capture</button>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
Javascript:
function capture() {
const captureElement = document.querySelector('#capture') // Select the element you want to capture. Select the <body> element to capture full page.
html2canvas(captureElement)
.then(canvas => {
canvas.style.display = 'none'
document.body.appendChild(canvas)
return canvas
})
.then(canvas => {
const image = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream')
const a = document.createElement('a')
a.setAttribute('download', 'my-image.png')
a.setAttribute('href', image)
a.click()
canvas.remove()
})
}
const btn = document.querySelector('#btn')
btn.addEventListener('click', capture)
Here's the JSFiddle
💡 QUICK TIP: If you want to capture the whole document/webpage, then just add the "capture" ID to the <body> tag.
If there is black background at image your chart must be visible on screen. Because html2canvas like a taking screenshot. If you want converting data
to canvas, you must be sure data is appear in screen.
In case someone is using React, here is some code you can copy:
async function download() {
const canvas = await html2canvas(document.querySelector("#screenshot"));
canvas.style.display = "none";
document.body.appendChild(canvas);
const image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
const a = document.createElement("a");
a.setAttribute("download", `info.png`);
a.setAttribute("href", image);
a.click();
}
<a href="#" onClick={() => download()}>Download</a>
This worked for me:
HTML
<div id="canvasDiv">
<canvas id="canvas" height="100" width="100">
Your browser does not support the HTML canvas tag.
</canvas>
</div>
<button onclick="screenShot()" type="button">Take a screenshot</button>
Javascript
function screenShot(){
html2canvas(document.querySelector("#canvasDiv")).then(canvas => {
var dataURL = canvas.toDataURL( "image/png" );
var data = atob( dataURL.substring( "data:image/png;base64,".length ) ),
asArray = new Uint8Array(data.length);
for( var i = 0, len = data.length; i < len; ++i ) {
asArray[i] = data.charCodeAt(i);
}
var blob = new Blob( [ asArray.buffer ], {type: "image/png"} );
saveAs(blob, "photo.png");
});
}
I just used the code provided in html2canvas site, then i used this code to download the screenshot.
I'm currently trying to make a solution, which needs me to be able to draw on top of a image.
I'm using sketch.js.
The problem is i need to copy the Base64 image instead of viewing it. So i can paste it into another program.
Is there any solution for this?
EDIT: The code is a website with one background, and sketch.js to draw lines on top of the background. Then i want to save the picture created in my clipboard, either the image or the base64 code.
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://rawgit.com/intridea/sketch.js/gh-pages/lib/sketch.js"></script>
<style>
body{ background-color: white; }
#wrapper{positon:relative;}
#bk,#myCanvas{position:absolute;}
</style>
<script>
$(function(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
$('#myCanvas').sketch({ defaultColor: "red" });
$('#download').click(function() {
var img=document.getElementById('bk');
ctx.globalCompositeOperation='destination-over';
ctx.drawImage(bk, 0, 0);
ctx.globalCompositeOperation='source-over';
var html="";
html+="<img src='"+c.toDataURL()+"' alt='from canvas'/>";
var tab=window.open();
tab.document.write(html);
});
}); // end $(function(){});
</script>
</head>
<body>
<h4>Hold to draw.</h4>
<button id=download>Save picture</button>
<div id="SketchTools">
<!-- Basic tools -->
<img src="img/black_icon.png" alt="Black"/>
<img src="img/red_icon.png" alt="Red"/>
<img src="img/green_icon.png" alt="Green"/>
<br/>
<!-- Size options -->
<img src="img/pencil_icon.png" alt="Pencil"/>
<img src="img/pen_icon.png" alt="Pen"/>
<img src="img/stick_icon.png" alt="Stick"/>
<img src="img/smallbrush_icon.png" alt="Small brush"/>
<img src="img/mediumbrush_icon.png" alt="Medium brush"/>
<img src="img/bigbrush_icon.png" alt="Big brush"/>
<img src="img/bucket_icon.png" alt="Huge bucket"/>
<br/>
</div>
<div id='wrapper'>
<img crossOrigin='anonymous' id=bk src='picturehere'>
<canvas id="myCanvas" width=800 height=600></canvas>
</div>
</body>
</html>
It is simple to copy to the clipboard but it does require user interaction. It can not be done automatically, or the data hidden, as that would pose a significant security risk. That said there is a work around using flash but personally I hope that hole is plugged soon.
So to the solution.
Add a textarea and a button labeled click. The image is copied to the textarea, clicking the button selects the text in the textarea and issue the cut command via document.execCommand('cut'); you could use 'copy' but cut gives some feed back.
I have tried to hide the textarea display:nonebut that blocks the cut, I have tried to issue the click event in code, that also blocked the cut/copy command
// this function is just here to draw a smile and add get the dataURL
// for the demo. It has no relevance to the problem
var smile = function(){
var image = document.createElement("canvas");
image.width = 32;
image.height =32;
var ct = image.getContext("2d"); // tack the context onto the image
var bp = function(){ct.beginPath();}
var p = Math.PI;
var pp = Math.PI*2;
var cx = cy = 16;
var s = function(){ct.stroke();}
var f = function(){ct.fill();}
var a = function(a1,a2,a3){bp(); ct.arc(cx,cy,a1,a2,a3)};
var af = function(a1,a2,a3){bp(); ct.arc(cx,cy,a1,a2,a3);f()};
var b = "black"
var w = "white";
var y = "yellow";
var col = function(a1,a2,a3){ ct.fillStyle = a1;ct.strokeStyle = a2;ct.lineWidth=a3;}
col(b,y);af(16,0,pp);col(y,b,2);af(14,0,pp);a(10,0.2,p-0.2);s();cx = 8;cy = 11;col(b,b,1);af(6,0,pp);col(w,b,1);af(5,0,pp);col(b,b,1);af(2,0,pp);cx = 24;af(6,0,pp);col(w,b,1);af(5,0,pp);col(b,b,1);af(2,0,pp);
// show the URL
imageShow.src = image.toDataURL("image/png");
// add the canvas URL base64 to the text area
textA.textContent = image.toDataURL("image/png");
}
//' get the elements we need
var textA = document.querySelector('#imgDat'); // text area that holds the URL
var imageShow = document.querySelector('#showIt'); // just to show whats being copied
var button = document.querySelector('#copyBut'); // the button to do it all;
smile(); // Create an image display it and put it in textArea
button.addEventListener("click",function(){
textA.select(); // select the content of the textArea
document.execCommand('cut'); // cut the selected content into
// cut/paste buffer
})
<textarea id="imgDat" ></textarea>
<img id="showIt"><input id="copyBut" type="button" value="COPY"><br>
Click to copy image as dataURL to clipboard.
Only Tested on chrome, and hope this helps.
I'm using expandablebanners.js on a rails site, the code I have to display the rollover image is;
<script type="text/javascript">
var roll_img = "<%= #advert.roll_img.url %>"
var squarecenterbottom = ExpandableBanners.banner("squarecenterbottom", roll_img);
squarecenterbottom.animated = true;
squarecenterbottom.setDirection('down', 'center');
squarecenterbottom.expandOnClick = false;
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded",function(){documentReady=true;});}
else if (!window.onload) window.onload = function(){documentReady=true;}
</script>
the main image is displayed on the page as so;
<%= link_to image_tag(#advert.img(:horizontal) title: #advert.name,),
#advert.target_url, :id => 'squarecenterbottom' %>
when you rollover the main image it should show the rollover image but
when I rollover the image it just shows the rollover image's url (i.e as text), I don't know what the problem is....
the code output is;
<script type="text/javascript">
var roll_img = "http://localhost:3000/system/adverts/large_imgs/000/000/004/original/1n.jpg?1401967781"
var squarecenterbottom = ExpandableBanners.banner("squarecenterbottom", roll_img );
squarecenterbottom.animated = true;
squarecenterbottom.setDirection('down', 'center');
squarecenterbottom.expandOnClick = false;
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded",function(){documentReady=true;});}
else if (!window.onload) window.onload = function(){documentReady=true;}
</script>
<img alt="test22" height="90" src="/system/adverts/imgs/000/000/004/horizontal/2n.jpeg?1401818651" title="test22" width="730" />
</div>
and this is the code from the documentation that shows how it works;
<script type="text/javascript">
var squaretopleft = ExpandableBanners.banner("squaretopleft", "images/square_expanded.jpg");
squaretopleft.setCloseImage("images/closebutton.jpg", 'left', 'top');
squaretopleft.animated = true;
squaretopleft.setDirection('up', 'left');
squaretopleft.expandOnClick = false;
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded",function(){documentReady=true;});}
else if (!window.onload) window.onload = function(){documentReady=true;}
</script>
</head>
<body>
<a id="squaretopleft" href="www.yourwebsite.com"><img src="images/square.jpg" /></a>
</body>
</html>
This might be a path or HTML structure problem.
Things to check:
In your output, your <a> element comes right after <script>. Then there is a </div> closing tag. Do you have an opening <div> before all? Are they all in the <body>?
Since ExpandableBanners code sets up onload and DOMContentLoaded listeners, try moving that in the <head> of the document.
Your original image has .jpeg extension and roll image has .jpg. Nothing wrong with this but make sure you have the correct images (and extensions) in the right paths. e.g. original image is under /imgs folder and roll is under /large_imgs. Is this ok?
Try relative path for your roll image. In this case: remove http://localhost:3000 in the beginning. (Assuming your original image is showing ok.)
Few points:
Missing semicolon at the end of var roll_img... declaration
As Ruby Racer mentioned, the generated anchor tag is missing double quote <a href="www.example.com
I am trying to create a function with javascript where a user upon clicking on an image can retrieve that images src as a URL. I am very new to javascript and my attempts so far at creating a function activated by "onclick" of an image are:
var showsrc = function(imageurl)
var img = new Image();
img.src = imageurl
return img.src
to call the results i have been trying to insert the image.src into my html using
document.getElementById("x").innerHTML=imageurl;
Im having very little success. Any help would be greatly appreciated. Thank you.
I tested this in IE9 and Chrome 17. Add an onclick handler to the body (or nearest container for all your images) and then monitor if the clicked element is an image. If so show the url.
http://jsfiddle.net/JbHdP/
var body = document.getElementsByTagName('body')[0];
body.onclick = function(e) {
if (e.srcElement.tagName == 'IMG') alert(e.srcElement.src);
};
I think you want something like this: http://jsfiddle.net/dLAkL/
See code here:
HTML:
<div id="urldiv">KEINE URL</div>
<div>
<img src="http://www.scstattegg.at/images/netz-auge.jpg" onclick="picurl(this);">
<img src="http://www.pictokon.net/bilder/2007-06-g/sonnenhut-bestimmung-pflege-bilder.jpg.jpg" onclick="picurl(this);">
</div>
JAVASCRIPT
picurl = function(imgtag) {
document.getElementById("urldiv").innerHTML = imgtag.getAttribute("src");
}
Image tags do not have an 'innerHTML', since they're singleton tags - they cannot have any children. If your x id is the image tag itself, then:
alert(document.getElementById('x').src);
would spit out the src of the image.
Here's a naïve solution with just javascript (probably not cross-browser compatible):
<!doctype html>
<html>
<head>
<script>
function init() {
var images = document.getElementsByTagName('img');
for(var i = 0, len = images.length; i < len; i++) {
images[i].addEventListener('click', showImageSrc);
}
}
function showImageSrc(e) {
alert(e.target.src);
}
</script>
</head>
<body onload="init()">
<img src="http://placekitten.com/300/300">
</body>
</html>
I'm pretty new to javascript and programming and have run into a brick wall with my project. I have a div which contains the javascript to embed a quicktime player, when the page is first loaded no .mov file is pointed at by the page so a placeholder div is 'unhidden' and the player div is set to style.display = 'none'.
So far so good, the user then enters the name of the new movie, the placeholder div is hidden and the player div is unhidden. My problem is that the javascript in the player div didn't run when the div was made visible, if I make the script for the player into a seperate function then call it when the player div is unhidden then the player runs full screen and not in the div.
I've tried using jquery to add the javascript into the div after the div is made visible but can't seem to get $("#player").load(somescript) or $("#player").html(htmlwithjavain) to add the script.
I know the player div contenst can be changed as I can use $("#player").empty(); and $("#player").html(); to manipulate it.
Thanks for reading, hope you can help
Here's the relevant code:-
<html>
<head>
<title>Browse Media Player</title>
<link rel="stylesheet" type="text/css" href="CSS/browser.css" />
<script type="text/javascript">
<!--
var userinterrupt=false;
var runonce=false;
var currentfile;
var basemediapath = "http://10.255.10.71/IsilonBrowse/movfiles/";
var playerheight = 750;
var playerwidth = 900;
var currenttc;
var basetime;
var baseduration;
var currentduration = "no tc available";
var tcoffset = 35990;
var playspeed = 1;
var boolisplaying=true;
var boolonslide=false;
//function to fire off other methods when the DOM is loaded
//Use in place of body onload, using jquery library
//
$(document).ready(function()
{
//showEvents('jquery running');
showhideplayer(null);
});
//-->
</script>
</head>
<body onload="forceslider(); timecode()">
<div class="container">
<div id="timecode_container">
<div class="tc_overlay"></div>
<div id="timecode" class="timecode"></div>
</div>
<div id="player" class="playerdiv" style="display:none;">
**javascript for player goes here...**
</div>
<div id="noclipoverlay" class="playerdiv" style="display:none;">
<p>No media loaded...
</div>
<div id="noclipoverlay2" class="playerdiv" style="display:none;">
<p>loading media....
</div>
</div>
<div id="loadstatus"></div>
<div id="alerts"></div>
</body>
</html>
Now the mainstuff.js file which should add the javascript code:-
//function to switch the player div and mask div is no media file is
//defined in the 'currentfile' variable
//
function showhideplayer(state)
{
if (!currentfile)
{
showEvents('wtf no media');
document.getElementById("player").style.display = 'none';
document.getElementById("noclipoverlay").style.display = 'block';
}
else if (currentfile)
{
document.getElementById("player").style.display = 'block';
document.getElementById("noclipoverlay").style.display = 'none';
showEvents('valid media file');
}
}
//end of showhideplayer
//function to change movie files, note SetResetPropertiesOnReload must be set to false
//otherwise the B'stard player will default all attributes when setURL runs
//
function changemovie(newmovie)
{
oldfile = currentfile;
if (newmovie == currentfile)
{
showEvents('same file requested so no action taken');
return;
}
if (newmovie != currentfile)
{
showEvents('changing movie');
//switch the divs around to hide the 'no media slide'
document.getElementById("player").style.display = 'block';
document.getElementById("noclipoverlay").style.display = 'none';
}
showEvents('movie changed to: '+newmovie);
currentfile=newmovie;
if (!oldfile)
{
$("#player").empty();
showEvents('the old media file was blank');
$("#player").load("/path/loadplayer.js");
}
document.movie1.Stop();
document.movie1.SetResetPropertiesOnReload(false);
document.movie1.SetURL(currentfile);
//showEvents('movie changed to: '+newmovie);
if (boolisplaying)
{
document.movie1.Play();
}
}
[EDIT] and here's the contents of loadplayer.js:-
var movie1 = QT_WriteOBJECT(
currentfile, playerwidth, playerheight, "",
"controller","false",
"obj#id", "movie1",
"emb#id","qt_movie1",
"postdomevents","True",
"emb#NAME","movie1",
"enablejavascript","true",
"autoplay","true",
"scale","aspect",
"pluginspage","http://www.apple.com/quicktime/download/"
);
Without knowing the content of your loadplayer.js file, it will be difficult to give you a solution.
For example, if the script attempts to do a document.write() after the page has loaded, it will create a new page, overwriting the current page. Is that what you mean when you say the quicktime movie is running full screen?
Also it is generally not a good idea to load a SCRIPT element and insert it as HTML. When you add HTML to the page, jQuery finds all the SCRIPT elements and evaluates them in a global context, which might give you unexpected results.
Use QT_GenerateOBJECTText_XHTML or QT_GenerateOBJECTText from AC_QuickTime.js if you'd like to return a string.