Skip to content

Instantly share code, notes, and snippets.

@mateuszkocz
Created August 6, 2013 17:14
Show Gist options
  • Save mateuszkocz/6166496 to your computer and use it in GitHub Desktop.
Save mateuszkocz/6166496 to your computer and use it in GitHub Desktop.
Drag & Drop, Canvas resize and upload a file. Source: http://davidwalsh.name/resize-image-canvas
var target = document.getElementById("drop-target");
target.addEventListener("dragover", function(e){e.preventDefault();}, true);
target.addEventListener("drop", function(e){
e.preventDefault();
loadImage(e.dataTransfer.files[0]);
}, true);
function loadImage(src){
// Prevent any non-image file type from being read.
if(!src.type.match(/image.*/)){
console.log("The dropped file is not an image: ", src.type);
return;
}
// Create our FileReader and run the results through the render function.
var reader = new FileReader();
reader.onload = function(e){
render(e.target.result);
};
reader.readAsDataURL(src);
}
var MAX_HEIGHT = 100;
function render(src){
var image = new Image();
image.onload = function(){
var canvas = document.getElementById("myCanvas");
if(image.height > MAX_HEIGHT) {
image.width *= MAX_HEIGHT / image.height;
image.height = MAX_HEIGHT;
}
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, image.width, image.height);
};
image.src = src;
}
// Uses DOJO. Can be any other AJAX technique.
// Remember that DTK 1.7+ is AMD!
require(["dojo/request"], function(request){
request.post("image-handler.php", {
data: {
imageName: "myImage.png",
imageData: encodeURIComponent(document.getElementById("canvas").toDataURL("image/png"))
}
}).then(function(text){
console.log("The server returned: ", text);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment