代码之家  ›  专栏  ›  技术社区  ›  fightstarr20

drawImage-调整大小并保持比例

  •  0
  • fightstarr20  · 技术社区  · 7 年前

    window.onload = function() {
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        var img = document.getElementById("scream");
        ctx.drawImage(img, 0, 0, 600, 428);
    }
    <p>Image to use:</p>
    <img id="scream" width="400" height="300" src="http://lorempixel.com/1280/960/sports/" alt="The Scream">
    
    <p>Canvas:</p>
    <canvas id="myCanvas" width="428" height="600" style="border:2px solid black;">
    Your browser does not support the HTML5 canvas tag.
    </canvas>

    我试图让图像填充容器,以丢失底部的空白,如果我放入精确的尺寸,那么它就会被拉伸。

    有没有人能给我举个例子?

    1 回复  |  直到 7 年前
        1
  •  3
  •   philipp    7 年前

    首先,您需要找到图像和画布的纵横比。这是由以下人员完成的:

    var canvasRatio = canvas.width / canvas.height,
        imgRatio = img.width / img.height,
        s = 1;
    

    然后你需要像这样比较这些比率:

    //the image is »more portrait«
    //to fully cover the canvas
    //scale by width
    if (imgRatio < canvasRatio) {
      s = canvas.width / img.width;
    
    //image has the same, or a »more landscape«
    //ratio than the canvas
    //to cover scale by height
    } else {
      s = canvas.height / img.height;
    }
    
    //scale the context
    ctx.scale(s, s);
    cts.drawImage(…);
    

    更新

    if ):

    var s = Math.max(canvas.width/img.width, canvas.height/img.height);
    

    Math.min