You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.3 KiB
JavaScript

// konva-utils.js
export function attachStageResizer(root, stage) {
const observer = new ResizeObserver(() => {
if (!stage) return;
stage.width(root.clientWidth);
stage.height(root.clientHeight);
stage.batchDraw();
});
observer.observe(root);
return observer;
}
// масштабирует картинку по stage
export function fitImageToStage(konvaImage, stage) {
const img = konvaImage.image();
const sw = stage.width();
const sh = stage.height();
const iw = img.naturalWidth;
const ih = img.naturalHeight;
const scale = Math.min(sw / iw, sh / ih);
konvaImage.width(iw);
konvaImage.height(ih);
konvaImage.scale({ x: scale, y: scale });
// центрируем
konvaImage.x((sw - iw * scale) / 2);
konvaImage.y((sh - ih * scale) / 2);
}
export function coverImageToStage(konvaImage, stage) {
const img = konvaImage.image();
const sw = stage.width();
const sh = stage.height();
const iw = img.naturalWidth;
const ih = img.naturalHeight;
const scale = Math.max(sw / iw, sh / ih);
konvaImage.width(iw);
konvaImage.height(ih);
konvaImage.scale({ x: scale, y: scale });
// центрируем и обрезаем по центру
konvaImage.x((sw - iw * scale) / 2);
konvaImage.y((sh - ih * scale) / 2);
}