javascript - 如何将图像缩放和居中为方形尺寸?
问题描述
这些问题相似但无济于事: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);
图片
解决方案
要在保留方面的同时将图像适合画布,请使用以下内容
const w = image.naturalWidth;
const h = image.naturalHeight;
// Get the min scale to fit the image to the canvas
const scale = Math.min(canvas.width / w, canvas.height / h);
// Set the transform to scale the image, and center to the canvas
ctx.setTransform(scale, 0, 0, scale, canvas.width / 2, canvas.height / 2);
// draw the image offset by half its width and height to center and fit
ctx.drawImage(image, -w / 2, -h / 2, w, h);
// to reset the transform
// ctx.setTransform(1,0,0,1,0,0);
推荐阅读
- c# - Asp.Net MVC ActionFilter 验证 xss 的查询参数
- fork - 使用 fork 创建多个进程并等待
- c++ - 访问具有这些子类数组的父类的子类中的变量,该数组本身在数组中?
- rust - 如何以原子方式使 Arc<> 删除 AtomicPtr
- python - 如何使用 Panda 遍历 .csv 中的列并将值返回到列表?
- tinymce - TinyMCE 和动态
- .net - powershell检查Assembly命令是否成功运行
- json - 在 C++Builder 中解析嵌套的 JSON 文件
- c++ - 为什么这不会创建一个悬空引用?
- javascript - 函数中的新对象总是在打字稿中返回相同的对象