如何将图像缩放和居中到正方形尺寸?

这些问题很相似,但没有帮助: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);

图片

http://img4.mukewang.com/618e20ed0001f0b705971294.jpg

哈士奇WWW
浏览 187回答 3
3回答

沧海一幻觉

这是我们使用的代码:    // 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);

临摹微笑

要在保留外观的同时使图像适合画布,请使用以下命令const w = image.naturalWidth;const h = image.naturalHeight;// Get the min scale to fit the image to the canvasconst scale = Math.min(canvas.width / w, canvas.height / h);// Set the transform to scale the image, and center to the canvasctx.setTransform(scale, 0, 0, scale, canvas.width / 2, canvas.height / 2);// draw the image offset by half its width and height to center and fitctx.drawImage(image, -w / 2, -h / 2, w, h);// to reset the transform// ctx.setTransform(1,0,0,1,0,0);

守着一只汪

假设我的计算方式正确,以下可能有效?ratio = image.width/image.height;if (image.width > image.height) {    output.height = ( 100 / ratio )     output.width = 100    output.x = 0    output.y = (100 - output.height) / 2} else {    output.height = 100    output.width = 100 * ratio    output.x = (100 - output.width) / 2    output.y = 0}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript