我正在使用 KonvaJS 创建一个简单的图像编辑器。作为图像调整功能的基础,我使用了 Konva 示例 ( Knonva JS Image Resize ) 中的代码。但现在我正在努力实现裁剪功能。在单击按钮时,我使用户能够在舞台上绘制一个矩形。然后我在我的图像上使用内置的裁剪功能,绘制矩形的坐标、宽度和高度并裁剪图像。但是,当我在裁剪之前调整图像大小时,裁剪区域会显示从原始大小的图像中裁剪出来的部分。
是否有一种简单的内置方式,我无法从调整大小的图像中进行裁剪?或者我是否必须根据图像的调整大小值计算绘制矩形的位置和大小,然后裁剪该部分并调整大小和重新定位结果?
裁剪图像:
function cropImage(x, y, width, height, activeLayer) {
var image = activeLayer.get('Image')[0], xDiff = 0, yDiff = 0, newWidth, newHeight, newX, newY;
// only Crop visible Parts of the Image
if(x < activeLayer.getX()) {
xDiff = activeLayer.getX() - x;
}
if(y < activeLayer.getY()) {
yDiff = activeLayer.getY() - y;
}
if (x + width > activeLayer.getX() + activeLayer.width()) {
width = width - ((x + width) - (activeLayer.getX() + activeLayer.width()));
}
if (y + height > activeLayer.getY() + activeLayer.height()) {
height = height - ((y + height) - (activeLayer.getY() + activeLayer.height()));
}
newHeight = height - yDiff;
newWidth = width - xDiff;
newX = (x - activeLayer.getX()) + image.cropX() + xDiff;
newY = (y - activeLayer.getY()) + image.cropY() + yDiff;
image.width(newWidth);
image.height(newHeight);
activeLayer.width(newWidth);
activeLayer.height(newHeight);
activeLayer.setX(newX + activeLayer.getX() - image.cropX());
activeLayer.setY(newY + activeLayer.getY() - image.cropY());
image.crop({
x : newX ,
y : newY ,
width : newWidth,
height : newHeight
});
//Reposition anchors so topLeft Anchor is always in 0/0 of the grouplayer
repositionAnchors(activeLayer);
activeLayer.draw();
}
调整大小时,我保留数组中宽度和高度的比率,并计算为裁剪绘制的矩形的位置和尺寸:
cropX = ((x / ratios[id].width) - (activeLayer.getX() / ratios[id].width)) + (image.cropX()) + (xDiff / ratios[id].width);
cropY = ((y / ratios[id].height)- (activeLayer.getY() / ratios[id].height)) + (image.cropY()) + (yDiff / ratios[id].height);
cropWidth = (width / ratios[id].width) - (xDiff / ratios[id].width),
cropHeight = (height / ratios[id].height) - (yDiff / ratios[id].height)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句