Save Canvas and Pop-up in new HTML window - javascript

My html 5 canvas is being saved to a server via php. It also pops up in a new window that is not html. The new window only contains the png image. I would like this new popup window to be able to share to social media. I know about auth2.0 and setting that up. What I don't know is how to get my png created from the saved canvas to popup on a new html page so I can add my social media tools. I am pretty sure it would be an edit to this line, window.open(testCanvas.toDataURL("images/png"));.
function saveImage() {
cursor.visible = false; stage.update();
var canvasData = testCanvas.toDataURL("image/png");
window.open(testCanvas.toDataURL("images/png"));
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
cursor.visible = true; stage.update();
}
else if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.open('POST', 'testSave.php', false);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function() {
console.log(ajax.responseText);
}
ajax.send("imgData="+canvasData);
}

New example without server side (using localStorage)
On the first page:
<input type="file" id="upfile" />
<script>
$ = function(id) { return document.getElementById(id); };
$('upfile').onchange = function(e) {
var files = e.target.files;
for (var i = 0; i < files.length; i++)
{
var f = files[i];
if (! f.type.match('image.*'))
continue;
var reader = new FileReader();
reader.onload = (function(filecontent) {
return function(ev) {
var b64data = ev.target.result;
localStorage.setItem('img', b64data);
window.open('popup.html', 'popup', 'width=600,height=400');
};
})(f);
reader.readAsDataURL(f);
}
};
</script>
In the popup page:
<img src="" id="thepicture" />
<script>
window.onload = function() {
document.getElementById('thepicture').src = localStorage.getItem('img');
};
</script>
Check the working demo here

Related

Multiple files upload with ajax

I'm trying to make a script to upload multiple files using ajax, and print them on the screen with a loading circle display.
The script is working for one file, but I have a problem to make it works for multiple files. I guess it a "scope" problem. But my JS knowledge is not that good.
Also, I'm only using standard JS, no jQuery.
Here's the script :
var index_div = 0;
var dropper = document.querySelector('#upload');
dropper.addEventListener('dragover', function(e) {
e.preventDefault(); // Annule l'interdiction de "drop"
}, false);
dropper.addEventListener('dragenter', function() {
dropper.style.borderStyle = 'solid';
});
dropper.addEventListener('dragleave', function() {
dropper.style.borderStyle = 'dashed';
});
dropper.addEventListener('drop', function(e) {
e.preventDefault();
dropper.style.borderStyle = 'dashed';
var files = e.dataTransfer.files,
filesLen = files.length;
for (var i = 0 ; i < filesLen ; i++) {
var NomImage = files[i].name;
if(files[i] != '')
{
if(window.XMLHttpRequest)
{
xhr=new XMLHttpRequest();
}
    else if(window.ActiveXObject)
{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
var newDiv = document.createElement("div");
newDiv.setAttribute("class","image_div");
document.getElementById("upload").appendChild(newDiv);
document.getElementsByClassName("image_div")[index_div].innerHTML = '<img id="chargement" src="../includes/chargement.gif"/>';
    var form = new FormData();
    form.append('file', files[i]);
xhr.open('POST', "./traitement_upload.php", true);
xhr.onload = function (e) {
if(xhr.readyState==4 && xhr.status==200)
{
      document.getElementsByClassName("image_div")[index_div].innerHTML =
xhr.responseText;
index_div += 1;
    }
}
    xhr.send(form);
}
}
});
Sorry for the sloppy code. If I check the xhr readyState and status during the loop, the first(s) are 1 and 0, then the last one is good.
You can see I'm creating a new div for each uploaded file so I can print a thumbnail in it.
For what I understand, the code is processing while the ajax request is not done yet. The result is I only see the last file I submitted.
If I put a false to the async flag on xhr.open, it works but it doesn't show the loading gif of course.
Thank you for your help.
You should extract the code for AJAX functionality in a separate function - otherwise the closure for xhr.onload will use the current (at the time of calling) value of index_div - most probably the last one from the FOR cycle. Also, querySelector returns a collection - even if it finds just a single element, or even if it finds nothing. Also, you should use both event.dataTransfer and event.target in order to handle both drag/drop and normal clicking.
var dropper = document.getElementById('upload');
dropper.addEventListener('dragover', function(e)
{
e.preventDefault();
dropper.style.background = '#eee';
}, false);
dropper.addEventListener('dragenter', function()
{
e.preventDefault();
dropper.style.background = '#eee';
}, false);
dropper.addEventListener('dragleave', function()
{
e.preventDefault();
dropper.style.background = '#fff';
}, false);
dropper.addEventListener('drop', uploadFile, false);
document.getElementById('file_upload').addEventListener('change', uploadFile, false);
function uploadFile(e)
{
e.preventDefault();
dropper.style.background = '#fff';
dropper.style.borderStyle = 'dashed';
var files = (e.dataTransfer || e.target).files,
filesLen = files.length;
for (var i = 0 ; i < filesLen ; i++)
{
if(files[i] != '')
{
var newDiv = document.createElement("div");
newDiv.setAttribute("class","image_div");
newDiv.innerHTML = '<img id="chargement" src="../includes/chargement.gif"/>';
document.getElementById("upload").appendChild(newDiv);
doAJAX(newDiv,files[i]);
}
}
}
function doAJAX(div,file)
{
var form = new FormData();
form.append('file', file);
if(window.XMLHttpRequest)
{
xhr=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('POST', "./traitement_upload.php", true);
xhr.onload = function (e)
{
if(xhr.readyState==4 && xhr.status==200)
{
div.innerHTML = xhr.responseText;
}
}
xhr.send(form);
}

How to insert Image in iframe using JavaScript?

I'm making my own rich text editor. So instead of inserting an image through URL, I'm doing through local files.
Iframe
<iframe style="width:100%; height: 300px;" name="richTextField"></iframe>
My Question is How to insert an image in an iframe?
function image()
{
$('#myModal').modal('show');
var file = document.getElementById("image").files;
$('#uploadImage').click(function(){
loadImageFileAsURL();
});
}
function loadImageFileAsURL()
{
var filesSelected = document.getElementById("image").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var imageLoaded = document.createElement("img");
imageLoaded.src = fileLoadedEvent.target.result;
//How to insert Image??
$('#myModal').modal('hide');
};
fileReader.readAsDataURL(fileToLoad);
}
}
}

Converting image dataUrl to Blob image for AJAX POST with javascript

I have the following code which will take an image, allow the user to crop (with other code not shown or necessary for this question), and then render the image in base64 from canvas.
I need to be able to convert the image to binary, as the API endpoint its being submitted to can't take base64. I have functionality to convert to a Blob, but I'm not sure how to implement it correctly:
$(function () {
var fileInput = document.getElementById("file"),
renderButton = $("#renderButton"),
submit = $(".submit"),
imgly = new ImglyKit({
container: "#container",
ratio: 1 / 1
});
// As soon as the user selects a file...
fileInput.addEventListener("change", function (event) {
var file;
var fileToBlob = event.target.files[0];
var blob = new Blob([fileToBlob], {
"type": fileToBlob.type
});
// do stuff with blob
console.log(blob);
// Find the selected file
if (event.target.files) {
file = event.target.files[0];
} else {
file = event.target.value;
}
// Use FileReader to turn the selected
// file into a data url. ImglyKit needs
// a data url or an image
var reader = new FileReader();
reader.onload = (function (file) {
return function (e) {
data = e.target.result;
// Run ImglyKit with the selected file
try {
imgly.run(data);
} catch (e) {
if (e.name == "NoSupportError") {
alert("Your browser does not support canvas.");
} else if (e.name == "InvalidError") {
alert("The given file is not an image");
}
}
};
})(file);
reader.readAsDataURL(file);
});
// As soon as the user clicks the render button...
// Listen for "Render final image" click
renderButton.click(function (event) {
var dataUrl;
imgly.renderToDataURL("image/jpeg", {
size: "1200"
}, function (err, dataUrl) {
// `dataUrl` now contains a resized rendered image
//Convert DataURL to Blob to send over Ajax
function dataURItoBlob(dataUrl) {
// convert base64 to raw binary data held in a string
var byteString = atob(dataUrl.split(',')[1]);
// separate out the mime component
var mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
//var bb = new BlobBuilder();
//bb.append(ab);
//return bb.getBlob(mimeString);
return new Blob([ab], {
type: 'image/jpeg'
});
}
var blob = dataURItoBlob(dataUrl);
//console.log("var blob: " + blob);
//var fd = new FormData(document.forms[0]);
var image = $("<img><br>").attr({
src: dataUrl
});
image.appendTo($(".result"))
$removeButton = $('<button class="btn btn-default remove">')
.text('Remove ' + imageid.value).appendTo($(".result"))
.on('click', function () {
panel.remove();
$(this).remove();
return false;
});
$submitButton = $('<div class="btn btn-default submit"></div>')
.text('Submit ' + imageid.value).appendTo($(".result"))
.on('click', function () {
var fd = new FormData;
fd.append('file', blob, 'image.png');
//console.log("var fd: " + fd);
var xhr = new XMLHttpRequest();
var saveImage = encodeURIComponent(dataUrl);
//console.log("SAVE IMAGE: " + saveImage);
//console.log(saveImage);
fd.append("myFile", blob);
xhr.open('POST', 'http://url.com/rest/v1/utils/guid/encode?' + saveImage + '&imageid=' + imageid.value, true);
xhr.send(fd);
});
});
});
});
On Submit, I get the following in the console:
http://url.com/rest/v1/utils/guid/encode?data%3Aimage%2Fjpeg%3Bbase64%2C%2F…CiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP%2FZ
The current version in jsFiddle: LINK

Read a local text file using Javascript

I have read some of the previous questions on this topic but I really need to be 100% sure!
Is it possible to read from a .txt file on my local system and present it in my HTML-BODY?
I have tried several functions, here is one:
function readFile (path) {
var fso = new ActiveXObject('Scripting.FileSystemObject'),
iStream=fso.OpenTextFile(path, 1, false);
while(!iStream.AtEndOfStream) {
document.body.innerHTML += iStream.ReadLine() + '<br/>';
}
iStream.Close();
}
readFile("testing.txt");
The content of the file is simply around 100 words I want to read from the text file and display in my HTML-BODY.
Is this possible without having my own server?
You can use a FileReader object to read text file here is example code:
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Here is the codepen demo
If you have a fixed file to read every time your application load then you can use this code :
<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
</script>
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>

Uncaught reference error BufferLoader is not defined

Trying to learn the Audio API, but I get an Uncaught reference error for BufferLoader class. I'm on chrome and it's up to date. Shouldn't this class be working with no problems?
<html>
<head>
<script type=text/javascript>
window.onload = init;
var context;
var bufferLoader;
function init(){
context = new webkitAudioContext();
bufferLoader = new BufferLoader(
context,
[
' https://dl.dropboxusercontent.com/u/1957768/kdFFO3.wav',
' https://dl.dropboxusercontent.com/u/1957768/geniuse%20meodies.wav',
],
finishedLoading
);
bufferLoader.load();
}
function finishedLoading(bufferList){
//make two sources and play them
var source1 = context.createBufferSource();
var source2 = context.createBufferSource();
source1.buffer = bufferList[0];
source2.buffer = bufferList[1];
source1.connect(context.destination);
source2.connect(context.destination);
source1.start(0);
source2.start(0);
}
</script>
</head>
<body>
</body>
</html>
The BufferLoader "class" is a custom function created to abstract the use of the Web Audio API. It's not a built-in feature, and must be included in your page in order to be used; there is nothing special about Chrome having this. Here's an example of where it is explained: http://www.html5rocks.com/en/tutorials/webaudio/intro/#toc-abstract
To use, include this code before it is used:
function BufferLoader(context, urlList, callback) {
this.context = context;
this.urlList = urlList;
this.onload = callback;
this.bufferList = new Array();
this.loadCount = 0;
}
BufferLoader.prototype.loadBuffer = function(url, index) {
// Load buffer asynchronously
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
var loader = this;
request.onload = function() {
// Asynchronously decode the audio file data in request.response
loader.context.decodeAudioData(
request.response,
function(buffer) {
if (!buffer) {
alert('error decoding file data: ' + url);
return;
}
loader.bufferList[index] = buffer;
if (++loader.loadCount == loader.urlList.length)
loader.onload(loader.bufferList);
},
function(error) {
console.error('decodeAudioData error', error);
}
);
}
request.onerror = function() {
alert('BufferLoader: XHR error');
}
request.send();
}
BufferLoader.prototype.load = function() {
for (var i = 0; i < this.urlList.length; ++i)
this.loadBuffer(this.urlList[i], i);
}

Categories