【问题标题】:Fit image to canvas by width and fit canvas to image new height按宽度使图像适合画布并使画布适合图像新高度
【发布时间】:2017-09-19 13:25:04
【问题描述】:

如何将比画布宽度更大的图像适应画布(带比例),然后在按宽度调整后将画布适应图像高度。

【问题讨论】:

    标签: html canvas


    【解决方案1】:

    // Create a variable for the canvas and it's context
    var canvas = document.getElementById("imageCanvas");
    var ctx = canvas.getContext("2d");
    
    // Initialise an image object
    var image = new Image();
    
    // When it loads an image
    image.onload = function() {
      // Get the canvas' current style
      var canvasStyle = getComputedStyle(canvas);
      
      // Get it's current width, minus the px at the end
      var canvasWidth = canvasStyle.width.replace("px", "");
      
      // Work out the images ratio
      var imageRatio = this.width/this.height;
      
      // Work out the new height of the canvas, keeping in ratio with the image
      var canvasHeight = canvasWidth/imageRatio;
      
      // Set the canvas' height in the style tag to be correct
      canvas.style.height = canvasHeight+"px";
      
      // Set the width/height attributes to be correct (as this is what drawImage uses)
      canvas.width = canvasWidth;
      canvas.height = canvasHeight;
      
      // Draw the image at the right width/height
      ctx.drawImage(this, 0, 0, canvasWidth, canvasHeight);
    };
    
    // Load an image
    image.src="https://placekitten.com/g/600/800";
    #imageCanvas
    {
      width: 400px;
      height: 400px;
    }
    <canvas id="imageCanvas" width="400px" height="400px"></canvas>

    你去吧,将图像缩小到正确的宽度,将画布的大小调整到正确的高度。希望 cmets 解释一切。

    【讨论】:

      猜你喜欢
      • 2021-06-13
      • 2020-10-24
      • 2019-05-12
      • 2014-04-11
      • 2014-05-31
      • 2015-04-28
      • 1970-01-01
      • 2020-11-27
      • 2013-01-03
      相关资源
      最近更新 更多