JS - 画布元素中的中心图像

时间:2016-09-21 14:54:24

标签: javascript html5 canvas

我正在缩小图像以使其适合画布内部,我正在努力做的事情就是将其置于canavas元素内部,有人知道如何做到这一点吗?任何帮助将不胜感激

https://jsfiddle.net/n7xL5c37/

var canvas = document.getElementById('canvas');
var image = new Image();
    image.src = 'http://placehold.it/300x550';
    image.onload = function () {
        var canvasContext = canvas.getContext('2d');
        var wrh = image.width / image.height;
        var newWidth = canvas.width;
        var newHeight = newWidth / wrh;
        if (newHeight > canvas.height) {
                    newHeight = canvas.height;
            newWidth = newHeight * wrh;
        }

        canvasContext.drawImage(image,0,0, newWidth , newHeight);
      };

4 个答案:

答案 0 :(得分:5)

    var canvas = document.getElementById('canvas');
    var image = new Image();
    image.src = 'http://placehold.it/300x550';
    image.onload = function () {
        var canvasContext = canvas.getContext('2d');
        var wrh = image.width / image.height;
        var newWidth = canvas.width;
        var newHeight = newWidth / wrh;
        if (newHeight > canvas.height) {
					newHeight = canvas.height;
        	newWidth = newHeight * wrh;
      	}
        var xOffset = newWidth < canvas.width ? ((canvas.width - newWidth) / 2) : 0;
        var yOffset = newHeight < canvas.height ? ((canvas.height - newHeight) / 2) : 0;

      	canvasContext.drawImage(image, xOffset, yOffset, newWidth, newHeight);
      };
<canvas id="canvas" width="500" height="500" style="border: 1px solid black" />

答案 1 :(得分:2)

适用于横向和纵向的解决方案。

首先找到适合宽度或高度的最小刻度的刻度

var scale = Math.min(canvas.width / img.width, canvas.height / img.height);

使用该比例来获取img宽度和高度

var w = img.width * scale;
var h = img.height * scale;

然后使用该比例计算左上角为距离中心的一半的距离

var left = canvas.width / 2 - w / 2;
var top = canvas.height / 2 - h / 2;

答案 2 :(得分:2)

如果你想要类似于object-fit: contain

的东西,路人的解决方案可以正常工作

如果您需要object-fit: cover

,此解决方案可以正常运行
const fitImageToCanvas = (image,canvas) => {
  const canvasContext = canvas.getContext("2d");
  const ratio = image.width / image.height;
  let newWidth = canvas.width;
  let newHeight = newWidth / ratio;
  if (newHeight < canvas.height) {
    newHeight = canvas.height;
    newWidth = newHeight * ratio;
  }
  const xOffset = newWidth > canvas.width ? (canvas.width - newWidth) / 2 : 0;
  const yOffset =
    newHeight > canvas.height ? (canvas.height - newHeight) / 2 : 0;
  canvasContext.drawImage(image, xOffset, yOffset, newWidth, newHeight);
};

答案 3 :(得分:-1)

您可以获得类似的元素:

var ctx = document.getElementById('digitalrain').getContext('2d');

然后将图像的x和y设置为:

ctx.drawImage(img, width/2-img.width/2, height/2-img.height/2);