【发布时间】:2017-09-19 13:25:04
【问题描述】:
如何将比画布宽度更大的图像适应画布(带比例),然后在按宽度调整后将画布适应图像高度。
【问题讨论】:
如何将比画布宽度更大的图像适应画布(带比例),然后在按宽度调整后将画布适应图像高度。
【问题讨论】:
// 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 解释一切。
【讨论】: