Reputation: 21
i'm quite new in the interaction between JS and Html and I'd like to know if it is possible to Upload an image through an HTML (a button or dropping it), and Display on JS Canvas so that I can modify it through Javascript pure, no jQuery.
So I can for example call the image like this: Image(img, 0, 0).. add a background or a point on it when the mouse is pressed.
I know that what I'm asking, and how I'm asking, can sound silly, but as i said I'm new in this subject.
I will appreciate any kind of help, as for example a link to similars question.
Thanks
Giovanni
Upvotes: 2
Views: 7203
Reputation: 4523
Maybe, you could try something like this ...
var fileUpload = document.getElementById('fileUpload');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
function readImage() {
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
var img = new Image();
img.src = e.target.result;
img.onload = function() {
ctx.drawImage(img, 0, 0, 512, 512);
};
};
FR.readAsDataURL( this.files[0] );
}
}
fileUpload.onchange = readImage;
canvas.onclick = function(e) {
var x = e.offsetX;
var y = e.offsetY;
ctx.beginPath();
ctx.fillStyle = 'black';
ctx.arc(x, y, 5, 0, Math.PI * 2);
ctx.fill();
};
#canvas {
border: 1px solid black;
margin-top: 10px;
}
<input type='file' id="fileUpload"/>
<canvas id="canvas" width="512" height="512"></canvas>
Upvotes: 2
Reputation: 490
The link to the original post: stackoverflow: javascript-upload-image-file-and-draw-it-into-a-canvas
Code:
function el(id){return document.getElementById(id);} // Get elem by ID
var canvas = el("canvas");
var context = canvas.getContext("2d");
function readImage() {
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
var img = new Image();
img.onload = function() {
context.drawImage(img, 0, 0);
};
img.src = e.target.result;
};
FR.readAsDataURL( this.files[0] );
}
}
el("fileUpload").addEventListener("change", readImage, false);
<input type='file' id="fileUpload" />
<canvas id="canvas" width="900" height="600"></canvas>
Upvotes: -1