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

问题描述 投票:0回答:1

我有一个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"/>
javascript jquery canvas
1个回答
1
投票

drawImage的第4和第5个参数是宽度和高度。下面的例子将占据整个画布。

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;
} 
© www.soinside.com 2019 - 2024. All rights reserved.