I have trouble downloading a dynamically created canvas. I want the user to be able to create an SVG image and download it as a bitmap. To achieve this, I create a canvas and draw my SVG image onto it. Then I want to download it. However, the canvas is blank. Now I know that this is probably because the canvas has not yet fully loaded, but attaching an onload listener on canvas didn't work as it never fired.
Clicking the link a second time downloads the correct image, another hint to me that it's a timing issue. Can someone tell me why the onload is never fired? Maybe I'm misunderstanding how the event is handled or what causes it.
document.getElementById('downloadDirectly').addEventListener('click', function () {
downloadDirectly();
});
document.getElementById('downloadOnLoad').addEventListener('click', function () {
downloadOnLoad();
});
function createCanvas() {
var img = new Image();
img.src = 'data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000"><line x1="0" y1="0" x2="500" y2="500" stroke="black" stroke-width="5"/></svg>';
var canvas = document.createElement('canvas');
canvas.width = 1000;
canvas.height = 1000;
canvas.getContext('2d').drawImage(img, 0, 0, 1000, 1000, 0, 0, 1000, 1000);
return canvas;
}
function downloadDirectly() {
let canvas = {};
canvas = createCanvas();
let el = document.getElementById('downloadDirectly');
el.href = canvas.toDataURL();
console.log('This downloads, but canvas is not ready');
el.download = name + ".png";
}
function downloadOnLoad() {
let canvas = {};
canvas = createCanvas();
canvas.onload = function() {
console.log('This is never reached :(');
let el = document.getElementById('downloadOnLoad');
el.href = canvas.toDataURL();
el.download = name + ".png";
};
}
<p><a id="downloadDirectly">Download directly</a></p>
<p><a id="downloadOnLoad">Download using onLoad</a></p>
Related
PS: Is it not a research kind of question! I have been trying to do this from very long time.
I am trying to make web based an image editor where user can select multiple cropping area and after selection save/download all the image area. like below.
As of now I discovered two libraries
1.Cropper.JS where is only single selection feature is available.
2.Jcrop where only single selection area restrictions.
I am currently using cropper.Js but it seems impossible for me to make multiple selection cropping.
Any help is much appreciated.if any other method/library available in JavaScript, Angular or PHP or reactJS for multiple image area selection and crop and download in one go as in the image below.
As per #Keyhan Answer I am Updating my Jcrop library Code
<div style="padding:0 5%;">
<img id="target" src="https://d3o1694hluedf9.cloudfront.net/market-750.jpg">
</div>
<button id="save">Crop it!</button>
<link rel="stylesheet" href="https://unpkg.com/jcrop/dist/jcrop.css">
<script src="https://unpkg.com/jcrop"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
JavaScript
<script>
setImage();
var jcp;
var jcp;
Jcrop.load('target').then(img => {
//You can enable multiple cropping with this line:
jcp = Jcrop.attach(img, { multi: true });
});
// to fix security issue when trying to convert to Data URI
function setImage() {
document.getElementById('target').setAttribute('crossOrigin', 'anonymous');
document.getElementById('target').src = 'https://d3o1694hluedf9.cloudfront.net/market-750.jpg';
}
var link = document.getElementById('save');
link.onclick = function () {
//we check if at least one crop is available
if (jcp.active) {
var i = 0;
var fullImg = document.getElementById("target");
//we are looping cropped areas
for (area of jcp.crops) {
i++;
//creating temp canvas and drawing cropped area on it
canvas = document.createElement("canvas");
canvas.setAttribute('width', area.pos.w);
canvas.setAttribute('height', area.pos.h);
ctx = canvas.getContext("2d");
ctx.drawImage(fullImg, area.pos.x, area.pos.y, area.pos.w, area.pos.h, 0, 0, area.pos.w, area.pos.h);
//creating temp link for saving/serving new image
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();
}
}
};
</script>
I tried to explain the code with comments:
var jcp;
Jcrop.load('target').then(img => {
//You can enable multiple cropping with this line:
jcp = Jcrop.attach(img,{multi:true});
});
//assuming you have a button with id="save" for exporting cropped areas
var link=document.getElementById('save');
link.onclick = function(){
//we check if at least one crop is available
if(jcp.active){
var i=0;
var fullImg = document.getElementById("target");
//we are looping cropped areas
for(area of jcp.crops){
i++;
//creating temp canvas and drawing cropped area on it
canvas = document.createElement("canvas");
canvas.setAttribute('width',area.pos.w);
canvas.setAttribute('height',area.pos.h);
ctx = canvas.getContext("2d");
ctx.drawImage(fullImg, area.pos.x, area.pos.y, area.pos.w, area.pos.h, 0, 0, area.pos.w, area.pos.h);
//creating temp link for saving/serving new image
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();
}
}
};
EDIT: As you commented it would be nicer if we have local image loader, we can add a file input to our html
<img id="target" />
<br/>
<input type="file" id="imageLoader" name="imageLoader"/><!-- add this for file picker -->
<button id="save">save</button>
and a function to our js to handle it
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});
});
Yes, #keyhan was right <input type="file"> is another question, but still, I am giving you an idea of how to implement Kayhan's code above.
<div>
<input type="file" id="image-input" accept="image/*">
<!-- img id name should be "target" as it is also using by Jcrop -->
<img id="target"></img>
</div>
and Now you can put below JavaScript Code just above setImage()
<script>
let imgInput = document.getElementById('image-input');
imgInput.addEventListener('change', function (e) {
if (e.target.files) {
let imageFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("img");
img.onload = function (event) {
var MAX_WIDTH = 1600;
var MAX_HEIGHT = 800;
var width = img.width;
var height = img.height;
// Change the resizing logic
if (width > height) {
if (width > MAX_WIDTH) {
height = height * (MAX_WIDTH / width);
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width = width * (MAX_HEIGHT / height);
height = MAX_HEIGHT;
}
}
// Dynamically create a canvas element
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
// var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Actual resizing
ctx.drawImage(img, 0, 0, width, height);
// Show resized image in preview element
var dataurl = canvas.toDataURL(imageFile.type);
document.getElementById("target").src = dataurl;
}
img.src = e.target.result;
}
reader.readAsDataURL(imageFile);
}
});
</script>
I have an issue I'm having a hard time believing... It seems that when I draw to a dynamically created canvas in Firefox it wont render the first time that source is run... It seems to happen the first time the JavaScript in question is run either by modifying the source or visiting the link for the first time. Here are some repro steps:
1) open a brand new instance of Firefox. visit the jsFiddle below.
2) see nothing
3) open a new tab in Firefox. visit the jsFiddle below.
4) see the result (10 colored squares)
Doing this in Chrome will result in seeing the result at both step 2 and step 4.
https://jsfiddle.net/sk873txv/1/
html
<body>
<div id="a">
</div>
</body>
js
$(document).ready(function(){
var make_canvas = function(i) {
var $canvas = $('<canvas>').appendTo($('#a'));
$canvas.attr('width', '100px');
$canvas.attr('height', '100px');
var canvas = $canvas[0];
var ctx = canvas.getContext('2d');
return ctx;
};
var draw = function(ctx) {
var image = new Image();
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkEAIAAACvEN5AAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAABa0lEQVR42u3cMU4CARRF0SeyWl0P7FaxoKbBuRrNOZUJCU7xcv9UvGzb7Xa6btvrddse/f2dT0+Xg77noOd58r9c/tTTPvr08hPPc962z7fBoc7b9mFYHEyxSCgWCcUioVgkDIuEU0hCsUgoFgnFImFYJJxCEopFQrFIKBaJe7Hef/sx+G8Ui4RhkfDyTkKxSCgWCcUiYVgknEISikVCsUgoFgnFIqFYJAyLhFNIQrFIKBYJxSJhWCScQhKKRUKxSCgWCcMi4RSSUCwSikVCsUgoFgnFImFYJJxCEvdi+eE1DqZYJLxjkTAsEk4hCcUioVgkFIuEYpFQLBKGRcIpJKFYJBSLhGKRMCwSTiEJxSKhWCQUi4RhkXAKSSgWCcUioVgkFIuEYpEwLBJOIQnFIqFYJBSLhGGRuJ9CP7zGwRSLhJd3EopFQrFIKBYJwyLhFJJQLBKKRUKxSBgWCaeQhGKRUCwSikVCsUh8ARsPyYz6AmddAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDExLTA0LTA3VDIxOjM2OjAyKzEwOjAwezv9bwAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxMS0wNC0wN1QyMTozNjowMisxMDowMApmRdMAAAA2dEVYdFBORzpiS0dEAGNodW5rIHdhcyBmb3VuZCAoc2VlIEJhY2tncm91bmQgY29sb3IsIGFib3ZlKbpeXNkAAAAVdEVYdFBORzpJSERSLmJpdF9kZXB0aAAxNqc4FdcAAAAVdEVYdFBORzpJSERSLmNvbG9yX3R5cGUAMgEnYzIAAAAbdEVYdFBORzpJSERSLmludGVybGFjZV9tZXRob2QAMPs7B4wAAAAedEVYdFBORzpJSERSLndpZHRoLGhlaWdodAAxMDAsIDEwMNtVy6kAAAAkdEVYdFBORzpwSFlzAHhfcmVzPTcyLCB5X3Jlcz03MiwgdW5pdHM9MKQw/n0AAAArdEVYdFBORzp0ZXh0ADIgdEVYdC96VFh0L2lUWHQgY2h1bmtzIHdlcmUgZm91bmRcYYD5AAAAAElFTkSuQmCC";
ctx.drawImage(image, 0, 0);
};
for(var i = 0; i < 10; i++)
{
draw(make_canvas(i));
}
});
You should wait for the load event to fire on the image, before drawing it to a canvas. Even though the image data is embedded as a data URI, there is no guarantee the image will be rendered and ready to draw the instant you set the src. Waiting for the load event will ensure the image is ready.
Working Example (JSFiddle):
$(document).ready(function(){
var make_canvas = function(i) {
var $canvas = $('<canvas>').appendTo($('#a'));
$canvas.attr('width', '100px');
$canvas.attr('height', '100px');
var canvas = $canvas[0];
var ctx = canvas.getContext('2d');
return ctx;
};
var draw = function(ctx) {
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkEAIAAACvEN5AAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAABa0lEQVR42u3cMU4CARRF0SeyWl0P7FaxoKbBuRrNOZUJCU7xcv9UvGzb7Xa6btvrddse/f2dT0+Xg77noOd58r9c/tTTPvr08hPPc962z7fBoc7b9mFYHEyxSCgWCcUioVgkDIuEU0hCsUgoFgnFImFYJJxCEopFQrFIKBaJe7Hef/sx+G8Ui4RhkfDyTkKxSCgWCcUiYVgknEISikVCsUgoFgnFIqFYJAyLhFNIQrFIKBYJxSJhWCScQhKKRUKxSCgWCcMi4RSSUCwSikVCsUgoFgnFImFYJJxCEvdi+eE1DqZYJLxjkTAsEk4hCcUioVgkFIuEYpFQLBKGRcIpJKFYJBSLhGKRMCwSTiEJxSKhWCQUi4RhkXAKSSgWCcUioVgkFIuEYpEwLBJOIQnFIqFYJBSLhGGRuJ9CP7zGwRSLhJd3EopFQrFIKBYJwyLhFJJQLBKKRUKxSBgWCaeQhGKRUCwSikVCsUh8ARsPyYz6AmddAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDExLTA0LTA3VDIxOjM2OjAyKzEwOjAwezv9bwAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxMS0wNC0wN1QyMTozNjowMisxMDowMApmRdMAAAA2dEVYdFBORzpiS0dEAGNodW5rIHdhcyBmb3VuZCAoc2VlIEJhY2tncm91bmQgY29sb3IsIGFib3ZlKbpeXNkAAAAVdEVYdFBORzpJSERSLmJpdF9kZXB0aAAxNqc4FdcAAAAVdEVYdFBORzpJSERSLmNvbG9yX3R5cGUAMgEnYzIAAAAbdEVYdFBORzpJSERSLmludGVybGFjZV9tZXRob2QAMPs7B4wAAAAedEVYdFBORzpJSERSLndpZHRoLGhlaWdodAAxMDAsIDEwMNtVy6kAAAAkdEVYdFBORzpwSFlzAHhfcmVzPTcyLCB5X3Jlcz03MiwgdW5pdHM9MKQw/n0AAAArdEVYdFBORzp0ZXh0ADIgdEVYdC96VFh0L2lUWHQgY2h1bmtzIHdlcmUgZm91bmRcYYD5AAAAAElFTkSuQmCC";
};
for(var i = 0; i < 10; i++)
{
draw(make_canvas(i));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div id="a">
</div>
</body>
I have a html5 canvas where you can erase the blur on top of an image. I would like to replace the blur with another image. I would like the end result to be once you erase the top image the bottom image will appear below it. I have been using an easeljs demo as a template.
http://www.createjs.com/#!/EaselJS/demos/alphamask
I feel like what I need to edit is in the html page script but it might be much deeper than that.
(Full code can be viewed here)
HTML
<canvas id="testCanvas" width="960" height="400"></canvas>
JavaScript
var stage;
var isDrawing;
var drawingCanvas;
var oldPt;
var oldMidPt;
var displayCanvas;
var image;
var bitmap;
var maskFilter;
var cursor;
var text;
var blur;
function init() {
if (window.top != window) {
document.getElementById("header").style.display = "none";
}
document.getElementById("loader").className = "loader";
image = new Image();
image.onload = handleComplete;
image.src = "images/summer.jpg";
stage = new createjs.Stage("testCanvas");
text = new createjs.Text("Loading...", "20px Arial", "#999999");
text.set({x:stage.canvas.width/2, y:stage.canvas.height-80});
text.textAlign = "center";
}
function handleComplete() {
document.getElementById("loader").className = "";
createjs.Touch.enable(stage);
stage.enableMouseOver();
stage.addEventListener("stagemousedown", handleMouseDown);
stage.addEventListener("stagemouseup", handleMouseUp);
stage.addEventListener("stagemousemove", handleMouseMove);
drawingCanvas = new createjs.Shape();
bitmap = new createjs.Bitmap(image);
blur = new createjs.Bitmap(image);
blur.filters = [new createjs.BoxBlurFilter(15,15,2)];
blur.cache(0,0,960,400);
blur.alpha = .5;
text.text = "Click and Drag to Reveal the Image.";
stage.addChild(blur, text, bitmap);
updateCacheImage(false);
cursor = new createjs.Shape(new createjs.Graphics().beginFill("#FFFFFF").drawCircle(0,0,20));
cursor.cursor = "pointer";
stage.addChild(cursor);
}
function handleMouseDown(event) {
oldPt = new createjs.Point(stage.mouseX, stage.mouseY);
oldMidPt = oldPt;
isDrawing = true;
}
function handleMouseMove(event) {
cursor.x = stage.mouseX;
cursor.y = stage.mouseY;
if (!isDrawing) {
stage.update();
return;
}
var midPoint = new createjs.Point(oldPt.x + stage.mouseX>>1, oldPt.y+stage.mouseY>>1);
drawingCanvas.graphics.setStrokeStyle(40, "round", "round")
.beginStroke("rgba(0,0,0,0.15)")
.moveTo(midPoint.x, midPoint.y)
.curveTo(oldPt.x, oldPt.y, oldMidPt.x, oldMidPt.y);
oldPt.x = stage.mouseX;
oldPt.y = stage.mouseY;
oldMidPt.x = midPoint.x;
oldMidPt.y = midPoint.y;
updateCacheImage(true);
}
function handleMouseUp(event) {
updateCacheImage(true);
isDrawing = false;
}
function updateCacheImage(update) {
if (update) {
drawingCanvas.updateCache(0, 0, image.width, image.height);
} else {
drawingCanvas.cache(0, 0, image.width, image.height);
}
maskFilter = new createjs.AlphaMaskFilter(drawingCanvas.cacheCanvas);
bitmap.filters = [maskFilter];
if (update) {
bitmap.updateCache(0, 0, image.width, image.height);
} else {
bitmap.cache(0, 0, image.width, image.height);
}
stage.update();
}
If you simply want to replace the blur-image, you have to change the following parts:
Add this after the loading of the first image:
image.src = "images/summer.jpg";
// add new part
image2 = new Image();
image2.onload = handleComplete;
image2.src = "images/your_newImage.jpg";
In the handleComplete() you now wait for 2 images to be loaded, so you add this:
function handleComplete() {
loaded++; // and initialize this variable in the very top with: var loaded = 0;
if ( window.loaded < 2 ) return;
//... other stull
and finally you change the following lines:
// old
blur = new createjs.Bitmap(image);
blur.filters = [new createjs.BoxBlurFilter(15,15,2)];
blur.cache(0,0,960,400);
blur.alpha = .5;
// new
blur = new createjs.Bitmap(image2);
This should now replace the blurred image with your desired image, it's not the best way, but it should get you there. I recommend you to start with some tutorial if you are planing to do more "deeper" stuff ;)
a common, though kinda janky, way is to re-size your canvas real quick. so changing your <canvas> elements width and height attributes. This will erase everything in your canvas.
Once that is done, reset it back to what you want it to be right away, and redraw the bottom image.
As I said this method is kinda sketchy but it does get the job done.
I want to load two separate images in my script. I've accomplished it using:
<img src="iphone4.png" id="img1">
<img src="screenshot.png" id="img2">
<script>
window.onload = function () {
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
</script>
Problem here though is that the images should not be visible on the page but are when loaded using markup. I simply want to load them through the script without first having to add them in the markup. I realize this is an extremely trivial problem, but searching for a solution has given me nothing.
I tried this approach:
window.onload = function () {
var img1 = "iphone4.png";
var img2 = "screenshot.png";
But this did not work.
Can someone with some common JS sense please give me some input on this issue.
EDIT :
So this is how the markup/JS looks now, the images are still displayed and the final merge of the images won't show. The error I get is:
IndexSizeError: Index or size is negative or greater than the allowed amount
[Stanna vid fel]
var image1 = context.getImageData(0, 0, width, height);
And this is the syntax:
<body>
<img src="" id="img1">
<img src="" id="img2">
<p>Blended image<br><canvas id="canvas"></canvas></p>
<script>
window.onload = function () {
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
img1.src = "iphone4.png";
img2.src = "screenshot.png";
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = img1.width;
var height = img1.height;
canvas.width = width;
canvas.height = height;
var pixels = 4 * width * height;
context.drawImage(img1, 0, 0);
var image1 = context.getImageData(0, 0, width, height);
var imageData1 = image1.data;
context.drawImage(img2, 73, 265);
var image2 = context.getImageData(0, 0, width, height);
var imageData2 = image2.data;
while (pixels--) {
imageData1[pixels] = imageData1[pixels] * 0 + imageData2[pixels] * 1;
}
image1.data = imageData1;
context.putImageData(image1, 0, 0);
};
</script>
You can create an Image without having the actual tag in the markup:
var img = new Image();
img.src = 'iphone4.png';
//use img however you want
Hope this helps.
window.onload = function () {
var img1 = new Image();
var img2 = new Image();
//EDIT2 you can hide img, or simply not add them to the DOM...
img1.style.display = "none";
img2.style.display = "none";
img1.src = "iphone4.png";
img2.src = "screenshot.png";
EDIT: DO NOT DO THAT and your images won't be displayed
document.body.append(img1);
OR
document.getElementById("myID").append(img2);
"What I'm doing is merging two images using JS"
Your problem is probably due to the fact that you are trying to draw images that have not been loaded yet. To circumvent this issue, you could create the images dynamically and set their src attribute to start loading the image and listen to the image's load event to know when they are fully loaded so that you can perform the merge safely.
I have not tested the code, but it should give you the idea.
var images = [
'iphone4.png',
'screenshot.png'
],
len = images.length,
i = 0,
loadedCount = 0,
img;
for (; i < len; i++) {
img = document.createElement('img');
//listener has to be added before setting the src attribute in case the image is cached
img.addEventListener('load', imgLoadHandler);
img.src = images[i];
images[i] = img;
}
function mergeImages() {
var img1 = images[0],
img2 = images[1];
//do the merging stuff
}
function imgLoadHandler() {
if (++loadedCount === len) {
mergeImages();
}
}
There is a way with HTML5, but it would still require the user to have dropped the file into a drop target or use a box.
Using the File API you can read files, and potentially decode them.
Actually reading the file blob and displaying it locally may be tricky though. You may be able to use the FileReader.readAsDataURL method to set the content as a data: URL for the image tag.
example:
$('#f').on('change', function(ev) {
var f = ev.target.files[0];
var fr = new FileReader();
fr.onload = function(ev2) {
console.dir(ev2);
$('#i').attr('src', ev2.target.result);
};
fr.readAsDataURL(f);
});
see the working fiddle here :
http://jsfiddle.net/alnitak/Qszjg/
using jquery:
$('#my_image').attr('src','image.jpg');
using javasript:
document.getElementById("my_image").src="image.jpg";
just check path to your image
Write the below code in head block
<script>
window.onload = function () {
document.getElementById("img1").src="iphone4.png";
document.getElementById("img2").src="screenshot.png";
}
</script>
This will work
Thanks
I would like to draw an image opened with the HTML5 File API on a canvas.
In the handleFiles(e) method, I can access the File with e.target.files[0] but I can't draw that image directly using drawImage. How do I draw an image from the File API on HTML5 canvas?
Here is the code I have used:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script>
window.onload = function() {
var input = document.getElementById('input');
input.addEventListener('change', handleFiles);
}
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.drawImage(e.target.files[0], 20,20);
alert('the image is drawn');
}
</script>
</head>
<body>
<h1>Test</h1>
<input type="file" id="input"/>
<canvas width="400" height="300" id="canvas"/>
</body>
</html>
You have a File instance which is not an image.
To get an image, use new Image(). The src needs to be an URL referencing to the selected File. You can use URL.createObjectURL to get an URL referencing to a Blob (a File is also a Blob): http://jsfiddle.net/t7mv6/86/.
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image;
img.onload = function() {
ctx.drawImage(img, 20,20);
alert('the image is drawn');
}
img.src = URL.createObjectURL(e.target.files[0]);
Note: be sure to revoke the object url when you are done with it otherwise you'll leak memory. If you're not doing anything too crazy, you can just stick a URL.revokeObjectURL(img.src) in the img.onload function.
References:
https://developer.mozilla.org/en/DOM/File
http://html5demos.com/file-api
Live Example
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
var url = URL.createObjectURL(e.target.files[0]);
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 20, 20);
}
img.src = url;
}
window.URL.createObjectUrldocs
You could also use the FileReader instead to create the object URL.
The FileReader has slightly better browser support.
The FileReader approach works in FF6 / Chrome. I'm not certain whether setting Img.src to a Blob is valid and cross-browser though.
Creating object urls is the correct way to do it.
Edit:
As mentioned in the commment window.URL support whilst offline seems unavailable in FF6/Chrome.
Here is a complete example (Fiddle) using FileReader (which has better browser support as mentioned by Raynos). In this example I also scale Canvas to fit the image.
In real life example you might scale the image to some maximum so that your form will not blow up ;-). Here is an example with scaling (Fiddle).
var URL = window.webkitURL || window.URL;
window.onload = function() {
var input = document.getElementById('input');
input.addEventListener('change', handleFiles, false);
// set original canvas dimensions as max
var canvas = document.getElementById('canvas');
canvas.dataMaxWidth = canvas.width;
canvas.dataMaxHeight = canvas.height;
}
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
var reader = new FileReader();
var file = e.target.files[0];
// load to image to get it's width/height
var img = new Image();
img.onload = function() {
// setup scaled dimensions
var scaled = getScaledDim(img, ctx.canvas.dataMaxWidth, ctx.canvas.dataMaxHeight);
// scale canvas to image
ctx.canvas.width = scaled.width;
ctx.canvas.height = scaled.height;
// draw image
ctx.drawImage(img, 0, 0
, ctx.canvas.width, ctx.canvas.height
);
}
// this is to setup loading the image
reader.onloadend = function () {
img.src = reader.result;
}
// this is to read the file
reader.readAsDataURL(file);
}
// returns scaled dimensions object
function getScaledDim(img, maxWidth, maxHeight) {
var scaled = {
ratio: img.width / img.height,
width: img.width,
height: img.height
}
if (scaled.width > maxWidth) {
scaled.width = maxWidth;
scaled.height = scaled.width / scaled.ratio;
}
if (scaled.height > maxHeight) {
scaled.height = maxHeight;
scaled.width = scaled.height / scaled.ratio;
}
return scaled;
}
canvas {
border:1px solid black
}
<input type="file" id="input"/>
<div>
<canvas width="400" height="300" id="canvas"/>
</div>