uploading an image and display in browser window - javascript

I have implemented a code in which image is uploaded into the browser and shown as thumbnail. Then it can also be dragged into a canvas area. But when i run it in chrome, it is not opening the window to upload the file. First the image is uploaded, then its thumbnail is created. But it is not working in chrome.
Here is my code,
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Drag Demo</title>
<link href="copy.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<div style = "border:2px solid black;">
<canvas id = "canvas" style = "position:relative;width:300px;height:300px;top:0px;left:500px; border:2px solid black;" ondrop="dropIt(event);" ondragover="event.preventDefault();"> </canvas>
</div>
<div>
<input type="file" id="fileElem" accept="image/*" style="display:none" >
<div id="fileSelect" class="drop-area">Select some files</div>
</div>
<div id="thumbnail"></div>
</div>
<script type="text/javascript">
function dragIt(event) {
event.dataTransfer.setData("Text", event.target.id)
};
function dropIt(event) {
var theData = event.dataTransfer.getData("Text");
dt = document.getElementById(theData);
event.preventDefault();
var c = document.getElementById("canvas");
var ctx = c.getContext('2d');
ctx.drawImage(dt, 100, 0,dt.width,dt.height);
};
var count = 0;
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem");
fileElem.addEventListener("click",function(e){
var files = this.files
handleFiles(files)
},false)
fileSelect.addEventListener("click", function (e) {
fileElem.click();
e.preventDefault();
}, false);
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if(!file.type.match(imageType)){
console.log("Not an Image");
continue;
}
var image = document.createElement("img");
var thumbnail = document.getElementById("thumbnail");
image.file = file;
thumbnail.appendChild(image)
var reader = new FileReader()
reader.onload = (function(aImg){
return function(e){
aImg.src = e.target.result;
};
}(image))
image.id = count;
count++;
image.draggable = true;
image.ondragstart = dragIt;
var ret = reader.readAsDataURL(file);
}
}
</script>
</body>
</html>

Just run the code on a server and it will work!

Related

How to resize Image on HTML Canvas while loading from client side?

I am trying to control Image size whenever user upload an Image, so when user upload larger image like 1600x1600 it should be fixed in a canvas with w=500 and h=800, how can I do this in canvas, also image quality have to be same only resize in image.
How can I set maxwidth and maxHeight to control the Image size ?
var jcp;
var save = document.getElementById('save');
var imageLoader = document.getElementById('imageLoader');
var img = document.getElementById("target");
imageLoader.onchange = function handleImage(e) { //handling our image picker <input>:
var reader = new FileReader();
reader.onload = function(event) {
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
save.onclick = function() {
if (jcp && jcp.active) {
var i = 0;
for (area of jcp.crops) {
i++;
canvas = document.createElement("canvas");
canvas.setAttribute('width', area.pos.w);
canvas.setAttribute('height', area.pos.h);
ctx = canvas.getContext("2d");
ctx.drawImage(img, area.pos.x, area.pos.y, area.pos.w, area.pos.h, 0, 0, area.pos.w, area.pos.h);
temp = document.createElement('a');
temp.setAttribute('download', 'area' + i + '.jpg');
temp.setAttribute('href', canvas.toDataURL("image/jpg").replace("image/jpg", "image/octet-stream"));
temp.click();
}
}
};
Jcrop.load('target').then(img => {
jcp = Jcrop.attach(img, {
multi: true
});
});
<head>
<title>Jcrop Example</title>
<link href="https://unpkg.com/jcrop#3.0.1/dist/jcrop.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://unpkg.com/jcrop#3.0.1/dist/jcrop.js"></script>
</head>
<body>
<div><a id="save">Save</a>
<input type="file" id="imageLoader" name="imageLoader" />
<!-- add this for file picker -->
</div>
<div>
<h1 style="font-family:Helvetica,sans-serif;">
Image Crop <span style="color:lightgray;"></span>
</h1>
<img id="target" style="background-size: cover !important;">
</div>
</body>
I'm not sure what is not working for you, but here I made a preview mode so you can see what's your crop result in canvas. If you wonder why the donwload not working, maybe it's SO snippets not allowed it, I'm not sure, but here you can test full working ecxample in jsfiddle
var jcp;
var save = document.getElementById('save');
var imageLoader = document.getElementById('imageLoader');
var img = document.getElementById("target");
var max_width = 500
var max_height = 500
var fileName = 'filename.png'
var changes
imageLoader.onchange = function handleImage(e) { //handling our image picker <input>:
var reader = new FileReader();
reader.onload = function(event) {
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
save.onclick = function() {
if (jcp && jcp.active) {
var i = 0;
for (let area of jcp.crops) {
i++;
let naturalWidth = img.naturalWidth;
let naturalHeight = img.naturalHeight;
let scaleX = naturalWidth / img.width
let scaleY = naturalHeight / img.height
let canvasSave = document.createElement("canvas");
var ctxSave = canvasSave.getContext('2d');
canvasSave.width = area.pos.w * scaleX
canvasSave.height = area.pos.h * scaleY
ctxSave.drawImage(img, -area.pos.x * scaleX, -area.pos.y * scaleY, naturalWidth, naturalHeight)
var link = document.createElement('a');
link.download = fileName;
link.href = canvasSave.toDataURL("image/png")
link.click();
alert('file save')
}
}
};
Jcrop.load('target').then(img => {
jcp = Jcrop.attach(img, {
multi: true,
});
changes = img.nextSibling
observer.observe(changes, config);
});
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
} else if (mutation.type === 'attributes') {
updatePreview()
}
}
};
const observer = new MutationObserver(callback);
const config = {
attributes: true,
childList: true,
subtree: true
};
function updatePreview() {
if (jcp && jcp.active) {
var i = 0;
for (let area of jcp.crops) {
canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
//for preview
canvas.width = area.pos.w
canvas.height = area.pos.h
ctx.drawImage(img, -area.pos.x, -area.pos.y, img.width, img.height)
}
}
}
<head>
<title>Jcrop Example</title>
<link href="https://unpkg.com/jcrop#3.0.1/dist/jcrop.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://unpkg.com/jcrop#3.0.1/dist/jcrop.js"></script>
</head>
<body>
<div><a id="save">Save</a>
<input type="file" id="imageLoader" name="imageLoader" />
<!-- add this for file picker -->
</div>
<div>
<h1 style="font-family:Helvetica,sans-serif;">
Image Crop <span style="color:lightgray;"></span>
</h1>
<img id="target" style="background-size: cover !important;" width='500'>
<div style='width:100%;'>
<canvas id="canvas" style='border: 4px solid blue;' />
</div>
</div>
</body>

Drag and drop images on div

I cant seem to be able to append the images to the ul inside the dropzone div.I want to have all the images appear horizontally, but so far when I drag images from desktop to the red square nothing happens.
This is something I extracted from the internet. Any help is appreciated.
var dropZone = document.getElementById('dropZone');
dropZone.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
dropZone.addEventListener('drop', function(e) {
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files;
for (var i=0, file; file=files[i]; i++) {
if (file.type.match(/image.*/)) {
var reader = new FileReader();
reader.onload = function(e2) {
// finished reading file data.
var img = document.createElement('img');
img.src= e2.target.result;
node.append(img);
document.getElementById('image_bar').appendChild(node);
}
reader.readAsDataURL(file); .
}
}
});
<div id="dropZone" style="width: 100px; height: 100px; background-color: red">
<div><ul id="image_bar"></ul></div>
</div>
First u need to remove the . on the line reader.readAsDataURL(file); . then when you run the code, you will see in the Console (F12 in chrome) that "node is not defined"
this code works:
create a file named myfile.html with this content:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hi</title>
</head>
<body>
<div id="dropZone" style="width: 100px; height: 100px; background-color: red">
<div><ul id="image_bar"></ul></div>
</div>
<script>
var dropZone = document.getElementById('dropZone');
dropZone.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
dropZone.addEventListener('drop', function(e) {
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files;
for (var i=0, file; file=files[i]; i++) {
if (file.type.match(/image.*/)) {
var reader = new FileReader();
reader.onload = function(e2) {
// finished reading file data.
var img = document.createElement('img');
img.src= e2.target.result;
document.getElementById('image_bar').appendChild(img);
}
reader.readAsDataURL(file);
}
}
});
</script>
</body>
</html>
This is how I would do it. Please read the comments in the code
var url = "";
dropZone.addEventListener("dragenter", dragenter, false);
dropZone.addEventListener("dragover", dragover, false);
dropZone.addEventListener("drop", drop, false);
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var data = e.dataTransfer;
var files = data.files;
handleFiles(files);
}
//a function to handle the dragged files
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
//a regEx to check if the dragged file is an image
var isImagen = /^image\//;
//if it's not an image
if (!isImagen.test(file.type)) {
continue;
}
//but if it's an image
var img = new Image();
img.src = window.URL.createObjectURL(file);
img.onload = function() {
var w = img.width;
var h = img.height;
//append the image to the image_bar
image_bar.appendChild(img);
window.URL.revokeObjectURL(this.src);
}
}
}
<div id="dropZone" style="width: 100px; height: 100px; background-color: red">
<div><ul id="image_bar"></ul></div>
</div>

Image upload preview javascript

I am trying to make a image preview before upload. But when i am trying to upload them, there are upload only the latest ones.
Example: Firstly i upload 3 images(and it appears 3 file selected), then i want to upload 4 more images. And my problem is that it appears 4 images selected(not 7 images selected) but in the image preview there are all of them.
I use python to upload them in the datastore and in the datastore there are only the latest images.
Javascript
//<![CDATA[
$(function(){
jQuery(function ($) {
var fileDiv = document.getElementById("upload");
var fileInput = document.getElementById("upload-image");
console.log(fileInput);
fileInput.addEventListener("change", function (e) {
var files = this.files
showThumbnail(files)
}, false)
function showThumbnail(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i]
var imageType = /image.*/
if (!file.type.match(imageType)) {
console.log("Not an Image");
continue;
}
var image = document.createElement("img");
// image.classList.add("")
var thumbnail = document.getElementById("thumbnail");
image.file = file;
thumbnail.appendChild(image)
var reader = new FileReader()
reader.onload = (function (aImg) {
return function (e) {
aImg.src = e.target.result;
};
}(image))
var ret = reader.readAsDataURL(file);
var canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
image.onload = function () {
ctx.drawImage(image, 100, 100)
}
}
}
});
});
//]]>
Html
<div class="row">
<div class="large-12 medium-12">
<input type="file" name='file' id="upload-image" multiple></input>
<div id="thumbnail">
</div>
</div>
</div>
Python
imagesnumber=len(self.get_uploads('file'))
while imagesnumber!=0:
image = self.get_uploads('file')[0]
img = DateBase()
img.blob_key = image.key()
img.img_url = images.get_serving_url( image.key() )
img.put()
imagesnumber=imagesnumber-1

Display image in canvas with Javascript?

I want to be able to click on a button on my page and load an image into a canvas at some X,Y coordinates?
The following code is what I have below. I would like the image to be in either image/photo.jpg or in the same directory but preferably in a subdirectory of the main page.
**Question: How to make a JPG show up in a canvas with the click of a button on the web page?
Code:
<!DOCTYPE html>
<html>
<script>
function draw(){
var ctx = document.getElementById("myCanvas").getContext("2d");
var img = new Image():
// img.src = "2c.jpg";
img.src = "/images/2c.jpg";
ctx.drawImage(img,0,0);
}
</script>
<body background="Black">
<div align="center">
<button type="button" onclick="draw()">Show Image on Canvas</button>
<canvas id="myCanvas" width="900" height="400" style="border:2px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="20px Arial";
ctx.fillText("Royal Flush $",500,50);
ctx.fillText("Striaght Flush $",500,80);
ctx.fillText("Flush $",500,110);
ctx.fillText("Four of a Kind $",500,140);
ctx.fillText("Full House $",500,170);
ctx.fillText("Three of a Kind $",500,200);
ctx.fillText("Two Pair $",500,230);
ctx.fillText("Pair of ACES $",500,260);
ctx.rect(495,10,270,350);
ctx.stroke();
</script>
</body>
</html>
March 6th, 2014 Code:
How is the following code not working. Do you have to have an ID tag on Canvas. The page will display but for some reason the image will not when the button is clicked. The image is in the same directory that my index.html file is in.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
canvas{
border: 5px solid black;
}
</style>
</html>
<button id="galaxy">Add image #1</button>
<button id="circles">Add image #2</button><span></span>
<canvas width="500" height="500"></canvas>
<script>
var Images = {};
function loadImages(list){
var total = 0;
document.querySelector("span").innerText = "...Loading...";
for(var i = 0; i < list.length; i++){
var img = new Image();
Images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
document.querySelector("span").innerText = "...Loaded.";
}
};
img.src = list[i].url;
}
}
function drawImage(img){
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(Images[img], 0, 0, 50, 50);
}
loadImages([{
name: "2c.jpg",
url: "mp.jpg"
},{
name: "mp.jpg",
url: "mp.jpg"
}]);
document.querySelector("#galaxy").addEventListener("click", function(){
drawImage("galaxy");
});
document.querySelector("#circles").addEventListener("click", function(){
drawImage("weirdCircles");
});
</script>
</html>
Wait till the image is loaded before drawing:
var img = new Image();
img.onload = function(){ /*or*/ img.addEventListener("load", function(){
ctx.drawImage(img,0,0); ctx.drawImage(img,0,0);
}; };
img.src = "/images/2c.jpg";
Demo: http://jsfiddle.net/DerekL/YcLgw/
If you have more than one image in your game,
It is better to preload all images before it starts.
Preload images: http://jsfiddle.net/DerekL/uCQAH/ (Without jQuery: http://jsfiddle.net/DerekL/Lr9Gb/)
If you are more familiar with OOP: http://jsfiddle.net/DerekL/2F2gu/
function ImageCollection(list, callback){
var total = 0, images = {}; //private :)
for(var i = 0; i < list.length; i++){
var img = new Image();
images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
callback && callback();
}
};
img.src = list[i].url;
}
this.get = function(name){
return images[name] || (function(){throw "Not exist"})();
};
}
//Create an ImageCollection to load and store my images
var images = new ImageCollection([{
name: "MyImage", url: "//example.com/example.jpg"
}]);
//To pick and draw an image from the collection:
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(images.get("MyImage"), 0, 0);

Image data transfer on drag and draw on canvas

I am uploading an image from PC. Then I read the file with file reader and display image by creating an img tag. Then I drag the image from the img tag into the canvas and draw it onto canvas. I'm using dragstart and onDrop events. I use datatransfer.setdata() and datatransfer.getdata() for the functionality. But on drop, the image drawn on canvas is not as original. It is a zoomed version. I don't know why is this happening!
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Drag Demo</title>
<link href="copy.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<div style = "border:2px solid black;">
<canvas id = "canvas" style = "position:relative;width:1000px;height:1000px;top:0px;left:200px; border:2px solid black;" ondrop="dropIt(event);" ondragover="event.preventDefault();"> </canvas>
</div>
<div>
<input type="file" id="fileElem" accept="image/*" style="display:none" >
<div id="fileSelect" class="drop-area">Select some files</div>
</div>
<div id="thumbnail"></div>
</div>
<script type="text/javascript">
function dragIt(event) {
event.dataTransfer.setData("URL", event.target.id)
};
function dropIt(event) {
var theData = event.dataTransfer.getData("URL");
dt = document.getElementById(theData);
alert(dt.width);
alert(dt.height);
event.preventDefault();
var c = document.getElementById("canvas");
var ctx = c.getContext('2d');
ctx.drawImage(dt, 0, 0);
};
var count = 0;
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem");
fileElem.addEventListener("change",function(e){
var files = this.files
handleFiles(files)
},false)
fileSelect.addEventListener("click", function (e) {
fileElem.click();
e.preventDefault();
}, false);
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if(!file.type.match(imageType)){
console.log("Not an Image");
continue;
}
var image = document.createElement("img");
var thumbnail = document.getElementById("thumbnail");
image.file = file;
function handlefilereader(evt){
var target = evt.target || evt.srcElement;
image.src = evt.target.result;
}
if(document.all) {
image.src = document.getElementById('fileElem').value;
}
else {
var reader = new FileReader()
reader.onload = handlefilereader;
reader.readAsDataURL(file);
}
image.id = count;
count++;
thumbnail.appendChild(image);
alert(image.width);
image.draggable = true;
image.ondragstart = dragIt;
}
}
</script>
</body>
</html>
With canvas there are 2 'size' settings:
Through CSS you'll set the DISPLAY size, so to set the PHYSICAL size of the canvas, you MUST use its attributes. So NO CSS/Style.
Think about it this way: you create a IMAGE with physical size: (let's say) 400px*400px.
Then just as a normal image (jpg,png,gif) that has a physical size, you can still choose to change the DISPLAYED size and thus aspect-ratio: like 800px*600px. Even % is normally supported.
Hope this explains clearly WHY this happened and why your solution in your comment is also the correct solution!!

Categories