Open 981377660LMT opened 9 months ago
/**
/**
初始时,图片的左上角与容器的左上角重合. */ export function calculateCenterAlignedImageTranslation ( imageWidth: number, imageHeight: number, containerWidth: number, containerHeight: number ): { translateX: number; translateY: number } { const solve = (imageSize: number, containerSize: number): number => { return (containerSize - imageSize) / 2; };
const translateX = solve(imageWidth, containerWidth); const translateY = solve(imageHeight, containerHeight); return { translateX, translateY }; }
2. contain 按照短边缩放,并且图片与容器中心对准;
代码将 `const ratio = Math.max(ratioX, ratioY)` 改成 `const ratio = Math.min(ratioX, ratioY)` 即可。
zrender 中使用
private _createFileItem (): Image {
const { file, style = {} } = this.props;
const containerWidth = style.width ?? 30;
const containerHeight = style.height ?? 30;
const { newWidth: fileWidth, newHeight: fileHeight } = scaleImageByBiggerRatio(
file.width ?? containerWidth,
file.height ?? containerHeight,
containerWidth,
containerHeight
);
const { translateX, translateY } = calculateCenterAlignedImageTranslation(fileWidth, fileHeight, containerWidth, containerHeight);
const fileProps: ImageProps = {
key: FileItem._fileKey,
name: file.name,
style: {
image: getImageByFile(file),
width: fileWidth,
height: fileHeight,
x: translateX,
y: translateY
},
z: style.z,
cursor: style.cursor,
clipPath: new Rect({
shape: {
width: containerWidth,
height: containerHeight,
r: style.borderRadius ?? 0
},
z: style.z,
silent: true
}),
onload: (imageLike) => {
// 图片加载失败时,显示默认图片
if (imageLike.height === 0) {
if ('src' in imageLike) {
imageLike.src = FILE_TYPE_ICON[FILE_TYPE.IMG];
}
}
// !图片load完后需要重新刷新整个组件,避免border被图片clip
this.render();
}
};
let fileItem = this.getReuseElement(FileItem._fileKey) as Image | undefined;
if (fileItem) {
fileItem.attr(fileProps);
} else {
fileItem = new Image(fileProps);
this._addHandler(fileItem, 'mouseover', (e) => {
this.props.onMouseEnter?.(e, this, fileItem!);
});
this._addHandler(fileItem, 'mouseout', (e) => {
this.props.onMouseLeave?.(e, this, fileItem!);
});
this._addHandler(fileItem, 'click', (e) => {
this.props.onClick?.(e, this, fileItem!);
});
}
return fileItem;
}
object-fit
属性通常用于<img>
或<video>
标签,用于控制这些元素的内容如何适应其容器的大小。以下是一些使用示例:object-fit: fill;
此设置会拉伸图片以填充容器,可能会改变图片的宽高比。
object-fit: contain;
此设置会保持图片的宽高比不变,同时尽可能地填充容器。如果容器的宽高比与图片的不同,可能会在容器中留下空白区域。
object-fit: cover;
此设置会保持图片的宽高比不变,同时尽可能地覆盖容器。如果容器的宽高比与图片的不同,可能会剪切掉图片的一部分。
object-fit: none;
此设置会保持图片的原始大小,忽略容器的大小。
object-fit: scale-down;
此设置会将图片的尺寸与
none
或contain
中较小的一个相同,也就是说,图片会尽可能地大,但是不会超过容器的大小,也不会超过图片的原始大小。