我尝试过别人的榜样 但是一旦图像宽度最大化,我就无法增加其高度。
这是我尝试过的示例https://jsfiddle.net/hq7gc0kd
我的代码片段中我可以分配顶部和左侧的位置,但是在with和height中并不能得到我期望的结果。要点是图像不应超出画布的范围,应在画布内部调整大小,帮助我
var canvas = new fabric.Canvas('c');
var image = "https://i.pinimg.com/originals/b6/22/dd/b622ddf656a4cd8d1174580213175ad1.jpg";
fabric.Image.fromURL(image, function(img) {
canvas.add(img);
img.left = canvas.width / 2 - img.getScaledWidth() / 2;
img.top = canvas.height / 2 - img.getScaledHeight() / 2;
canvas.on("object:scaling", function(e) {
/** Getting needed Properties of image */
var shape = e.target,
maxWidth = canvas.width,
maxHeight = canvas.height,
actualWidth = shape.scaleX * shape.width,
actualHeight = shape.scaleY * shape.height,
currentScaleX = shape.scaleY,
shapeLeft = shape.left,
shapeTop = shape.top;
/**Conditional with and height will be improved here ,i have blocked in this section */
if (shapeLeft < 0 || shapeTop < 0 ||
actualWidth + shapeLeft >= maxWidth ||
actualHeight + shapeTop >= maxHeight) {
shape.set({
left: 5,
top: 5,
/* having doubt this values */
width: actualWidth, //example
height: actualHeight, //example
/* or */
/* scaleX:5
scaleY:5 */
})
}
});
});
<canvas id="c" width="360" height="360" style="border:1px solid #000000;"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.7.0/fabric.js"></script>