Pet*_*r I 7 canvas html5-canvas fabricjs
如何缩放图像以正确适合容器尺寸?我想要一个两个图像和每个图像的网格,以适应提供的大小.
https://codepen.io/peteringram0/pen/gebYWo?editors=0010
img.set({
left: 0,
top: 0,
width: 300,
height: 300
// Scale image to fit width / height ?
});
Run Code Online (Sandbox Code Playgroud)
编辑:对不起,我没有非常清楚地解释我的问题.我希望将其定位在网格中,但作为"封面"类型.https://codepen.io/peteringram0/pen/xWwZmy?editors=0011.例如,在链接中,网格中有4个图像,但图像位于中心并且溢出.我想让每个图像垂直居中,没有超出设定大小的溢出.谢谢(x应该在中心,同时保持纵横比)
Abd*_*eeb 13
如果要将图像对象缩放到给定的宽度或高度,请分别使用scaleToWidth和scaleToHeight.
我从你的代码中删除了img.set函数中指定的高度和宽度.并添加了scaeToHeight和scaleToWidth方法.使用以下代码.
window.fabric.Image.fromURL(`https://images.unsplash.com/photo-1430418372158-66adfd0d88cb?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=a074583d6ecf670af630fa2a15bc82ef&auto=format&fit=crop&w=1353&q=80`, (img) => {
img.set({
left: 300,
top: 0
});
img.scaleToHeight(300);
img.scaleToWidth(300);
canvas.add(img);
})
Run Code Online (Sandbox Code Playgroud)
看看这个小提琴:https://jsfiddle.net/hazeebp/195uan6f/1/