通过宽度使图像适合画布并使画布适合新图像

时间:2017-09-19 13:25:04

标签: html5 canvas

如何将画布宽度较大的图像放入画布(带刻度),然后在宽度适合后将画布调整到图像高度。

1 个答案:

答案 0 :(得分:2)



// 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>
&#13;
&#13;
&#13;

你去,将图像缩小到合适的宽度,将画布调整到合适的高度。希望评论解释一切。