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

新手上路,请多包涵

我正在缩小图像以使其适合画布,我正在努力做的事情是将其置于 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);
      };

原文由 NoDachi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 185
2 个回答
     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" />

原文由 Passersby 发布,翻译遵循 CC BY-SA 3.0 许可协议

适用于水平和垂直的解决方案。

首先找到适合宽度或高度的最小比例尺

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;

原文由 Blindman67 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题