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

drawImage将图像大小调整为500px高

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

    我试图采取的图像是1280x960和调整它使用drawImage,使其是600像素高。我已经计算出了我认为需要达到的比例,但不知道如何应用。。。

    var canvas = document.getElementById('mycanvas');
    var ctx = canvas.getContext('2d');
    var img = new Image();
    img.onload = function () {
      canvas.height = this.height;
      canvas.width = this.width;
      
      ratio = canvas.height / canvas.width;
      
      console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);
      
      ctx.drawImage(img, 0, 0, 300, 500);
    }
    img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
    <canvas id="mycanvas"></canvas>

    如何指定生成的图像大小,使宽度自动?我最终希望这个函数将任何图像的大小调整到500像素高。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Julio Feferman Mohamed Mostafa Goda    7 年前

    这里有一个解决方案,有点迂回,但似乎可行。我使用创建了一个新图像 toDataURL() 从原始尺寸的画布。虽然新图像已缩小,但总尺寸仍然是原始图像的尺寸,因此剩余空间是透明的。然后我将这个图像设置并剪辑到一个新的画布上。生成的画布具有大小正确的图像,可以按所需尺寸复制和粘贴。

    https://jsfiddle.net/jfeferman/u80fhy0z/

    var canvas = document.getElementById('mycanvas');
    var ctx = canvas.getContext('2d');
    var img = new Image();
    img.crossOrigin = "Anonymous";
    img.onload = function () {
      canvas.height = this.height;
      canvas.width = this.width;
      
      ratio = canvas.height / canvas.width;
      
      console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);
      
      ctx.drawImage(img, 0, 0, 500 / ratio, 500);
      
      var newImage = new Image();
      newImage.crossOrigin = "Anonymous";
      newImage.src = canvas.toDataURL();
      
      var newCanvas = document.getElementById("newcanvas");
      newCanvas.height = 500;
      newCanvas.width = 500 / ratio;
      var newCtx = newCanvas.getContext('2d');
      newCtx.drawImage(newImage, 0, 0, 500 / ratio, 500, 0, 0, 500 / ratio, 500);
    }
    img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
    #mycanvas {
      display: none;
    }
    <canvas id="newcanvas"></canvas>
    <canvas id="mycanvas"></canvas>
        2
  •  1
  •   Julio Feferman Mohamed Mostafa Goda    7 年前

    我将这个比例应用到您对drawImage的调用中,它似乎起到了作用:

    ctx.drawImage(img, 0, 0, 500 / ratio, 500);
    

    var canvas = document.getElementById('mycanvas');
    var ctx = canvas.getContext('2d');
    var img = new Image();
    img.onload = function () {
      canvas.height = this.height;
      canvas.width = this.width;
      
      ratio = canvas.height / canvas.width;
      
      console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);
      
      ctx.drawImage(img, 0, 0);
      canvas.style.width = 500 / ratio + "px";
      canvas.style.height = 500 + "px";
    }
    img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
    <canvas id="mycanvas"></canvas>