这些问题很相似,但无济于事:this、this、this和this。
目标是在正方形画布上绘制图像,同时保留原始纵横比,如果原始纵横比不是正方形,则将图像居中。
例如,以附加的1262x2688图像为例。下面的代码将其大小调整为100x100,但它会扭曲纵横比。
代码应该:(1)缩放图像以适应100x100画布;(2)保留纵横比;(3)在画布中垂直和水平居中图像。
// Create canvas element.
var canvas = $(document.createElement("canvas"));
// Get canvas context.
var context = canvas[0].getContext("2d");
// Set canvas size.
canvas[0].width = 100;
canvas[0].height = 100;
// Write image to canvas.
context.drawImage(image, 0, 0, newWidth, newHeight);图像

发布于 2019-10-13 08:40:32
下面是我们使用的代码:
// Create canvas element.
var canvas = $(document.createElement("canvas"));
// Get canvas context.
var context = canvas[0].getContext("2d");
// Set canvas size.
canvas[0].width = canvasWidth;
canvas[0].height = canvasHeight;
// Set image size, must use image.naturalWidth and image.naturalHeight -- not image.width and image.height.
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
// Set scale to fit image to canvas,
const scale = Math.min(canvasWidth/imageWidth, canvasHeight/imageHeight);
// Set new image dimensions.
const scaledWidth = imageWidth * scale;
const scaledHeight = imageHeight * scale;
// Draw image in center of canvas.
context.drawImage(image, (canvasWidth - scaledWidth)/2, (canvasHeight - scaledHeight)/2, scaledWidth, scaledHeight);https://stackoverflow.com/questions/58278575
复制相似问题