Draw image to canvas with Pixabay API (Jquery) - javascript

The JSFIDDLE
Here is my problem:
I want to draw the image in the second line of the console when I double click on "Get JSON DATA", in my canvas.
I hope that was clear.
I think it's a bit difficult...
Here is my code :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<canvas id="test1" width="200px" height="200px"> </canvas>
<input id="urlBanner" type="text" style="width:450px;" maxlength="100">
<button type="button" value="Get JSON Data" onclick="getUrlBanner()">Get JSON data</button>
<script>
function getUrlBanner()
{
var urlBanner = document.getElementById("urlBanner").value;
console.log(urlBanner);
var urlAPI = "https://pixabay.com/api/?key=10642718-3227f97c509ef5fe89537eec9&q=";
//var full = "full:" + urlBanner;
//console.log(full);
$(document).ready(function(){
$("button").click(function(){
fetch(urlAPI+urlBanner+"&image_type=photo")
.then(res => res.json())
.then((out) => {
var img = out.hits[0].largeImageURL;
document.getElementById('test1').src = img;
console.log(img);
console.log("full : " + urlAPI+urlBanner+"&image_type=photo");
}).catch(err => console.error(err));
});
});
}
$(document).ready(function() {
$('#test1').each(function() {
var myCanvas = document.getElementById('test1');
var ctx = document.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(img[0],10,10);
};
img.src = 'UrlBanner';
});
});
</script>
</body>
</html>
My API works properly, that's ok.
In fact, the problem is really here I think
$(document).ready(function() {
$('#test1').each(function() {
var myCanvas = document.getElementById('test1');
var ctx = document.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(img[0],10,10);
I can't get it...
The jpg file in console need to appear in my canvas.
Thanks in advance,

Related

How to get value of input type = file and display it on a dynamically created image?

I have the following code:
function displayImg() {
let fileUpload = document.getElementById("fileUpload").value;
let container document.getElementById("container");
container.innerHTML = `<img src="fileUpload">`
}
<input type = file id = "fileUpload" accept = "image/*">
<button onclick = "displayImg()">Click to show</button>
<div id="container"></div>
I want it so that the user can input the file into the file Input field and it is placed into the source of a dynamically-created image upon button click. How do I do this?
You can try this
<html>
<body>
<input type = file id = "fileUpload" accept = "image/*">
<button onclick = "displayImg()">Click to show</button>
<div id="container">
<img id="img"></div>
<script>
function displayImg() {
let fileUpload = document.getElementById("fileUpload").value;
//alert(fileUpload);
let image = document.getElementById("img");
img.src = fileUpload;
}
</script>
</body>
</html>
NOTE: The value property only returns the name of the file so the image should be located in the same folder as that of code.Or if you want to, you can add the path of the file before.
please use the below code:
var uploadedFileURL;
function handleFile() {
var fileUploadControl = document.getElementById('fileUpload');
var file = fileUploadControl.files[0];
if (file) {
var reader = new FileReader();
reader.onload = function() {
uploadedFileURL = reader.result;
};
reader.readAsDataURL(file);
}
}
function displayImg() {
var fileUpload = document.getElementById("fileUpload").value;
var container = document.getElementById("container");
container.innerHTML = `<img src="${uploadedFileURL}">`;
}
<input id="fileUpload" type="file" onchange="handleFile()" accept="image/*" />
<button onclick="displayImg()">Click to show</button>
<div id="container"></div>
Here is a solution :
<input type="file" id="fileUpload" accept="image/*">
<button onclick="displayImg()">Click to show</button>
<div id="container">
<img id="img"></img>
</div>
<script>
let displayImg = () => {
let reader = new FileReader();
let input = document.getElementById('fileUpload');
reader.onload = () => {
let img = document.getElementById('img');
img.src = reader.result;
};
reader.readAsDataURL(input.files[0]);
};
</script>

preview the uploaded .pdf file in ASP web form

I am building an ASP webform application. I used
<asp:FileUpload runat="server" ID="fubillPhoto" onchange="showPreviewBill(this);" />
...to upload a pdf file. I want users to be able to review the uploaded file before submitting the form.
My idea is to create an element. When the user clicks on it a new tab open with PDF file. unfortunately I could not apply my idea... Here is my code:
HTML
<asp:FileUpload runat="server" ID="fuBillPhoto" onchange="showPreviewBill(this);" />
<div runat="server" id="divPdfBill" class="hidden">
<a runat="server" id="pdfBilllink" href="#" target="_blank">click here</a>
</div>
=====
Javascript
function showPreviewBill(input) {
var pdfLink = document.getElementById('#<%=pdfBilllink.ClientID %>');
var file = document.querySelector('#<%=fubillPhoto.ClientID %>').files[0];
var reader = new FileReader();
reader.onloadend = function () {
if (reader.result) {
$('#<%=pdfBilllink.ClientIDMode %>').attr("href", reader.result);
$('#<%=divPdfBill.ClientID %>').attr("class", "");
}
}
$('#<%=pdfBilllink.ClientIDMode %>').attr("href", reader.result);
It does not work! Please advise.
Load data uri from input file control use javascript file api.
Convert data uri to binary.
Show binary data in canvas using PDF.js.
here is a reference on how to do that with code
[link] https://forums.asp.net/t/2062665.aspx?Preview+pdf+file+before+upload
code from above reference website
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../Scripts/jquery-1.10.2.js"></script>
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#pdfInp").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
showInCanvas(e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
function convertDataURIToBinary(dataURI) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
function showInCanvas(url) {
// See README for overview
'use strict';
// Fetch the PDF document from the URL using promises
var pdfAsArray = convertDataURIToBinary(url);
PDFJS.getDocument(pdfAsArray).then(function (pdf) {
// Using promise to fetch the page
pdf.getPage(1).then(function (page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
// Prepare canvas using PDF page dimensions
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
});
}
});
</script>
</head>
<body>
<form id="form1" >
<p>
<input type='file' id="pdfInp" />
<canvas id="the-canvas" style="border:1px solid black"></canvas>
</p>
</form>
</body>
</html>
<asp:FileUpload runat="server" ID="fubillPhoto" onchange="showPreviewBill(this);"
/>`enter code here`

JavaScript - Reading file with HTML5 FileReader

I'm currently learning JavaScript and I'm struggling to read a txt file and use its contents in the program, what I have so far:
fileBtn.addEventListener("change", function()
{
var content = [];
var file = fileBtn.files[0];
readFile(file, function(data)
{
console.log(JSON.parse(data));
//content.push(JSON.parse(data)) doesn't work, data is undef.
});
});
and a function readFile
function readFile(file, f)
{
var reader = new FileReader();
reader.onload = function(evt)
{
f(evt.target.result);
};
reader.readAsText(file);
}
My txt file is currenty only containing a "1", and it logs this number to the console but I can't work with it, if I try to push it into an array the values is suddenly undefined. My goal is to use the content of the file in the program later on
1 . no need to use JSON.parse if the text file only contain string .
data is containing all the text file content
2 . you need to put var content = [];
globally and not inside the function readFile
follow this snippet of code i think it will solve your problem
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<label for="file-upload" class="custom-file-upload">
Custom Upload
</label>
<input id="file-upload" type="file" />
<input id="log-content" type="button" value="Click Me"/>
</body>
<script>
var content = [];
function readFile(file, f) {
var reader = new FileReader();
reader.onload = function (evt) {
f(evt.target.result);
};
var text = reader.readAsText(file);
}
var fileBtn = document.getElementById("file-upload");
var logContnt = document.getElementById("log-content");
logContnt.addEventListener("click", function () {
alert(content);
})
fileBtn.addEventListener("change", function () {
var file = fileBtn.files[0];
readFile(file, function (data) {
content.push(data);
});
});
</script>
</html>

JS/HTML - Removing item before querying again

I have some code that grabs images from an API and it all works fine however, I can't figure out how to remove the original query before the other is displayed.
Open to other methods as well.
<html>
<body>
<div>Stock History Graph :</div>
<form>
<input type="text" value="" id="imagename"/>
<input type="button" id="btn" value="Update" />
</form>
<script type="text/javascript">
document.getElementById('btn').onclick = function() {
var val = document.getElementById('imagename').value,
src = 'http://chart.finance.yahoo.com/z?s=' + val +'.AX'+'&t=6m&q=l&l=on&z=s&p=m50,m200"',
img = document.createElement('img');
img.src = src;
document.body.appendChild(img);
}
</script>
</body>
</html>
Create the img variable outside of the onclick function, then in the onclick function all you have to do is set the src of the image.
Right now you're creating a new element every time you click the button.
Check if Image already there just update src, no need to create tag again.
document.getElementById('btn').onclick = function() {
var val = document.getElementById('imagename').value,
src = 'http://chart.finance.yahoo.com/z?s=' + val +'.AX'+'&t=6m&q=l&l=on&z=s&p=m50,m200"',
img = document.getElementById("chart-comp") || document.createElement('img');
img.id = "chart-comp"
img.src = src;
document.body.appendChild(img);
}
Check this fiddle

Getting file contents via FileReader() JavaScript

I am trying to get file contents with FileReader(), JavaScript.
I find this answer: https://stackoverflow.com/a/21962101/2898694
As #Markasoftware said in comments, I am trying to save result to var.
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var myFile = evt.target.files[0];
var reader = new FileReader();
var result;
reader.readAsText(myFile);
reader.onload=function(){
result = reader.result;
console.log(result); // works
}
console.log(result); // not works
}
If I am trying to see content in onload handler all fine, but out of it I can't see result. Why?
Because onload runs asynchrone. console.log(result); // not works is executed before the onload event has fired.
More on that: How do I return the response from an asynchronous call?
example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var sizef = document.getElementById('uploadImage').files[0].size;
document.getElementById("uploadPreview").src = oFREvent.target.result;
document.getElementById("uploadImageValue").value = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var imgUrl = $('#uploadImageValue').val();
alert(imgUrl);
});
});
</script>
<div>
<input type="hidden" id="uploadImageValue" name="uploadImageValue" value="" />
<img id="uploadPreview" style="width: 150px; height: 150px;" /><br />
<input id="uploadImage" style="width:120px" type="file" size="10" accept="image/jpeg,image/gif, image/png" name="myPhoto" onchange="PreviewImage();" />
</div>
Source file
</body>
</html>

Categories