this code draws an image of the user’s local computer on a canvas then slide it on some other canvases for slide puzzle game
function drawImage(event) {
if (event.target.files.length <= 0) return;
var files = event.target.files;
var URL = window.URL || window.webkitURL;
var img = $("#image")[0];
img.src = URL.createObjectURL(files[0]);
getCanvas("karajan").drawImage(img, 0, 0, img.width, img.height, 0, 0, 450, 450);
...........
}
function getCanvas(id) {
var canvas = $("#" + id)[0];
if (canvas.getContext) {
return canvas.getContext("2d");
}
return undefined;
}
and a tag that inputs image file from local computer
<input type="file" accept="image/*" id="image_input" onchange="drawImage(event)"/>
<img id="image"/>
and when user want to change the image, the canvas will draw with previous image. I don’t know why. in the first lines of drawImage function image changes with newer image and draws on canvas
I assume the image is not actually “loaded” until the current script terminates. That means you should listen to the load event of the image and only then draw it to the canvas.
I did some restructuring of your code as well. If you already have jQuery available, use it:
You should still clear the canvas though, as Kolink suggested. Otherwise, if a new, smaller image is loaded, parts of the previous, larger image will still be visible.