上传的图片填充画布Javascript

时间:2016-10-22 07:46:21

标签: javascript canvas

我想通过将画布大小设置为图像的大小来使上传的图像填充画布的大小。画布大小设置正确但图像变小,并且不会填充画布。如何让图像填满画布?这是我到目前为止所尝试过的。

<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);
}

1 个答案:

答案 0 :(得分:0)

           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);}

这是你的HTML代码

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