如何在画布元素中获取整个图像?

时间:2019-04-20 10:14:41

标签: javascript jquery canvas

我有一个canvas元素,想在里面加载entire图像。
画布的最大宽度应为50%。
加载的图像具有不同的宽度和高度,但是无论如何我都需要整个图像而不是其中的一部分。
可能吗?

var URL = window.webkitURL || window.URL;

window.onload = function() {
    var input = document.getElementById('input');
    input.addEventListener('change', handleFiles, false);
}

function handleFiles(e) {
    var ctx = document.getElementById('canvas').getContext('2d');
    var url = URL.createObjectURL(e.target.files[0]);
    var img = new Image();
    img.onload = function() {
        ctx.drawImage(img, 10, 10);    
    }
    img.src = url;
    
}
#canvas{
max-width:50%;
}
<input type="file" id="input"/>
<canvas id="canvas"/>

1 个答案:

答案 0 :(得分:1)

drawImage的第4和第5参数是width和height。下面的示例将占据整个画布。

var URL = window.webkitURL || window.URL;

window.onload = function() {
  var input = document.getElementById('input');
  input.addEventListener('change', handleFiles, false);
}

function handleFiles(e) {
  var ctx = document.getElementById('canvas').getContext('2d');
  var url = URL.createObjectURL(e.target.files[0]);
  var img = new Image();
  img.onload = function() {
    ctx.drawImage(img, 0, 0, ctx.canvas.width, ctx.canvas.height);
  }
  img.src = url;


}
#canvas {
  background-color: salmon;
  max-width: 50%;
}
<input type="file" id="input" />
<canvas id="canvas" />


如果您想要比例图像,我们可以在此处使用solution进行计算

var URL = window.webkitURL || window.URL;

window.onload = function() {
  var input = document.getElementById('input');
  input.addEventListener('change', handleFiles, false);
}

function handleFiles(e) {
  var ctx = document.getElementById('canvas').getContext('2d');
  var url = URL.createObjectURL(e.target.files[0]);
  var img = new Image();
  img.onload = function() {

    var newDimen = calculateAspectRatioFit(img.width, img.height, ctx.canvas.width, ctx.canvas.height);
    ctx.drawImage(img, 0, 0, newDimen.width, newDimen.height);
  }
  img.src = url;
}

function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
  var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
  return {
    width: srcWidth * ratio,
    height: srcHeight * ratio
  };
}
#canvas {
  background-color: salmon;
  max-width: 50%;
}
<input type="file" id="input" />
<canvas id="canvas" />


如果要集中式图像,可以:

function handleFiles(e) {
    var ctx = document.getElementById('canvas').getContext('2d');
    var url = URL.createObjectURL(e.target.files[0]);
    var img = new Image();
    img.onload = function() {

        var newDimen = calculateAspectRatioFit( img.width, img.height, ctx.canvas.width, ctx.canvas.height );
        var tSpace = ( ctx.canvas.height - newDimen.height ) / 2;
        var lSpace = ( ctx.canvas.width - newDimen.width ) / 2;
        ctx.drawImage(img, lSpace, tSpace, newDimen.width, newDimen.height);
    }
    img.src = url;
}