julekgwa julekgwa - 1 month ago 9
Javascript Question

Uploaded image fill canvas Javascript

I'm want to make the uploaded image to fill the size of the canvas, by setting the canvas size to the size of the image. The canvas size is set correctly but the image becomes smaller, and doesn't fill the canvas. How can I make the image fill the canvas? here's what I've tried so far.

<canvas id="canvas" style="border: 1px solid #000; width: 400px; height: 300px"></canvas>
<input type="file" name="photo" id="image" accept="image/*">


JS

var image = document.getElementById('image');
var canvas = document.getElementById('canvas');
var canvasWidth = 400;
var canvasHeight = 300;

if (image) {
image.addEventListener('change', function () {
var context = canvas.getContext('2d');
if (this.files && this.files[0]) {
var fr = new FileReader();
fr.onload = function (ev) {
var img = new Image();
img.onload = function () {
canvasWidth = img.width;
canvasHeight = img.height;
canvas.style.width = canvasWidth + 'px';
canvas.style.height = canvasHeight + 'px';
context.drawImage(img, 0, 0);
};
img.src = ev.target.result;
};
fr.readAsDataURL(this.files[0]);
}
}, false);
}

Answer
           var image = document.getElementById('image');
var canvas = document.getElementById('canvas');
var canvasWidth = 400;
var canvasHeight = 300;

if (image) {
image.addEventListener('change', function () {
var context = canvas.getContext('2d');
if (this.files && this.files[0]) {
var fr = new FileReader();
fr.onload = function (ev) {
var img = new Image();
img.onload = function () {
canvasWidth = img.naturalWidth;
canvasHeight = img.naturalHeight;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
context.drawImage(img, 0, 0, canvasWidth, canvasHeight);
};
img.src = ev.target.result;
};
fr.readAsDataURL(this.files[0]);
}
 }, false);}

here is you html code

<canvas id="canvas" width="400" height="300" style="border:1px solid red"></canvas>
<input type="file" name="photo" id="image" accept="image/*">