在画布中调整图像大小

时间:2018-03-28 13:21:00

标签: javascript canvas

我正在尝试将图片加载并调整为416x416。但是我仍然可以获得相同的图像尺寸。

代码:

var ctx = canvas.getContext('2d');

function readURL(input) {
    if(input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {;
            var image = new Image();
            image.src = e.target.result
            image.addEventListener("load",function(){
             ctx.drawImage(image, 0, 0, 416,416)
            })
        }
        reader.readAsDataURL(input.files[0]);
    }
}

我已经阅读了很多关于此的帖子,但是一切都表明代码应该是正确的,我在哪里做错了?

1 个答案:

答案 0 :(得分:1)

如果您没有设置画布大小,可能会出现这种情况。

如果没有设置画布大小,则调整大小不起作用:



const width = 416;
const height = 416;

let canvas = document.querySelector('canvas')
//canvas.width = width;
//canvas.height = height;

function readURL(input) {
  let ctx = canvas.getContext('2d');
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {;
      var image = new Image();
      image.src = e.target.result
      image.addEventListener("load", function() {
        ctx.drawImage(image, 0, 0, width, height)
      })
    }
    reader.readAsDataURL(input.files[0]);
  }
}

<!DOCTYPE html>
<html>
<body>
  <input type="file" onchange="readURL(this)" />
  <canvas></canvas>
</body>
</html>
&#13;
&#13;
&#13;

如果设置了画布大小,则调整大小:

&#13;
&#13;
const width = 416;
const height = 416;

let canvas = document.querySelector('canvas')
canvas.width = width;
canvas.height = height;

function readURL(input) {
  let ctx = canvas.getContext('2d');
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {;
      var image = new Image();
      image.src = e.target.result
      image.addEventListener("load", function() {
        ctx.drawImage(image, 0, 0, width, height)
      })
    }
    reader.readAsDataURL(input.files[0]);
  }
}
&#13;
<!DOCTYPE html>
<html>
<body>
  <input type="file" onchange="readURL(this)" />
  <canvas></canvas>
</body>
</html>
&#13;
&#13;
&#13;