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>
Related
I can load an image into a canvas element and resize it, but I'm having trouble grabbing the resized image:
var logo = $(".logo"),
loader = $(".load"),
canvas = $(".holder"),
ctx = canvas[0].getContext("2d");
function displayPreview(file) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = e.target.result;
img.onload = function() {
// x, y, width, height
ctx.drawImage(img, 0, 0, 128, 128);
var dataURL = canvas[0].toDataURL("image/png");
var logo = $(".logo");
var imgUrl = dataURL;
var imgz = $("<img>");
imgz.attr("src", imgUrl);
logo.html("");
logo.append(imgz);
};
};
reader.readAsDataURL(file);
}
into the download package function for jszip.
// Download Zip
$(".download").on("click", function(imgUrl) {
var zip = new JSZip();
zip.file("logo.png", imgUrl);
var content = zip.generate({type:"blob"});
// see FileSaver.js
saveAs(content, "test.zip");
});
Snippet:
var logo = $(".logo"),
loader = $(".load"),
canvas = $(".holder"),
ctx = canvas[0].getContext("2d");
function displayPreview(file) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = e.target.result;
img.onload = function() {
// x, y, width, height
ctx.drawImage(img, 0, 0, 128, 128);
var dataURL = canvas[0].toDataURL("image/png");
var logo = $(".logo");
var imgUrl = dataURL;
var imgz = $("<img>");
imgz.attr("src", imgUrl);
logo.html("");
logo.append(imgz);
};
};
reader.readAsDataURL(file);
}
$(document).ready(function() {
loader.on("change", function(evt) {
var file = evt.target.files[0];
displayPreview(file);
var reader = new FileReader();
reader.onload = function(e) {
// Download Zip
$(".download").on("click", function(imgUrl) {
var zip = new JSZip();
zip.file("logo.png", imgUrl);
var content = zip.generate({type:"blob"});
// see FileSaver.js
saveAs(content, "test.zip");
});
return false;
};
reader.readAsArrayBuffer(file);
});
// Trigger Load Image
$(".trigload").click(function() {
$("input").trigger("click");
});
});
#import url("http://necolas.github.io/normalize.css/3.0.1/normalize.css");
.hide {
display: none;
}
.logo {
text-align: center;
}
.fill {
width: 100%;
}
.fr {
float: right;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip-utils/dist/jszip-utils.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip/vendor/FileSaver.js"></script>
<input type="file" class="hide load">
<a class="trigload" href="javascript:void(0)">Load Image</a>
<a class="download fr" href="javascript:void(0)">Download</a>
<div class="logo"></div>
<div class="fill" align="center">
<canvas class="holder" width="128" height="128"></canvas>
</div>
In order to get JSZip to correctly save your dataURL to valid png file, it seems you need to add an object containing {base64: true}as third argument of the zip.file() method, and to remove the data:image/png;base64, from the dataURL.
Also, you were assigning the click event to the imgUrl variable. You may want to store it in a global variable, or check the $('.logo>img')[0].src or call once again canvas[0].toDataURL().
var logo = $(".logo"),
loader = $(".load"),
canvas = $(".holder"),
ctx = canvas[0].getContext("2d");
function displayPreview(file) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.src = e.target.result;
img.onload = function() {
// x, y, width, height
ctx.drawImage(img, 0, 0, 128, 128);
var dataURL = canvas[0].toDataURL("image/png");
var logo = $(".logo");
var imgUrl = dataURL;
var imgz = $("<img>");
imgz.attr("src", imgUrl);
logo.html("");
logo.append(imgz);
};
};
reader.readAsDataURL(file);
}
$(document).ready(function() {
loader.on("change", function(evt) {
var file = evt.target.files[0];
displayPreview(file);
var reader = new FileReader();
reader.onload = function(e) {
// Download Zip
$(".download").on("click", function() {
var imgUrl = canvas[0].toDataURL();
var zip = new JSZip();
zip.file("logo.png", imgUrl.split('base64,')[1],{base64: true});
var content = zip.generate({type:"blob"});
// see FileSaver.js
saveAs(content, "test.zip");
});
return false;
};
reader.readAsArrayBuffer(file);
});
// Trigger Load Image
$(".trigload").click(function() {
$("input").trigger("click");
});
});
#import url("http://necolas.github.io/normalize.css/3.0.1/normalize.css");
.hide {
display: none;
}
.logo {
text-align: center;
}
.fill {
width: 100%;
}
.fr {
float: right;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip-utils/dist/jszip-utils.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip/vendor/FileSaver.js"></script>
<input type="file" class="hide load">
<a class="trigload" href="javascript:void(0)">Load Image</a>
<a class="download fr" href="javascript:void(0)">Download</a>
<div class="logo"></div>
<div class="fill" align="center">
<canvas class="holder" width="128" height="128"></canvas>
</div>
2022 Edit
JSZip now accepts Blobs as input directly, so it's better to convert your canvas to a Blob and pass this directly to JSZip. (As a fiddle because StackSnippets don't allow-downloads).
can you help me with this? I am searching for how can add images with a upload or with existing images with select button, then draw in the image and for last save it into DB like a rute of the image is (ex. images/canvas/draw1.jpg or .png)
I follow this two tutorials...but I am not know how finish it
select-diferent-image-for-canvas-background
dynamically-add-image-to-canvas
This example lets your user drag an image from their desktop onto the background canvas:
var canvas = document.getElementById("bk");
var bkctx = canvas.getContext("2d");
// dropzone event handlers
var dropzone;
dropzone = document.getElementById("dropzone");
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 dt = e.dataTransfer;
var files = dt.files;
handleFiles(files);
}
//
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
// get the next file that the user selected
var file = files[i];
var imageType = /image.*/;
// don't try to process non-images
if (!file.type.match(imageType)) {
continue;
}
// a seed img element for the FileReader
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
// get an image file from the user
// this uses drag/drop, but you could substitute file-browsing
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.onload = function() {
// draw the aImg onto the canvas
bkctx.clearRect(0, 0, canvas.width, canvas.height);
bkctx.drawImage(aImg, 0, 0);
}
// e.target.result is a dataURL for the image
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
} // end for
} // end handleFiles
body {
background-color: ivory;
}
#dropzone {
border: 1px solid blue;
position: relative;
width: 300px;
height: 300px;
}
canvas {
border: 1px solid red;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Drag an image from desktop to blue dropzone.</h4>
<div id="dropzone" width=300 height=300>
<canvas id="bk" width=300 height=300></canvas>
<canvas id="canvas" width=300 height=300></canvas>
</div>
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
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!!
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!