简体   繁体   English

通过不使用组 fabric.js 缩放矩形来缩放图像

[英]scale image by scaling rectangle without group fabric.js

I am new in fabric.js and want to achieve one functionality I added image and one rectangle same size of image, now I want to scale image while scaling rectangle.我是 fabric.js 的新手,想要实现一项功能,我添加了图像和一个相同大小的图像矩形,现在我想在缩放矩形的同时缩放图像。 I don't want to group objects, image should scale by scaling rectangle with previous left, top position of image我不想对对象进行分组,图像应该通过缩放矩形来缩放,左上角是图像的顶部 position

below is my code下面是我的代码

 var imgURL = 'http://i.imgur.com/8rmMZI3.jpg'; var canvas = new fabric.Canvas('canvas'); var pug; var pugImg = new Image(); pugImg.onload = function (img) { pug = new fabric.Image(pugImg, { angle: 0, width: 500, height: 500, left: 50, top: 70, scaleX: .25, scaleY: .25, selectable: false }); var rect = new fabric.Rect({ top: 65, left: 200, width: 150, height: 150, fill: 'red', }); canvas.sendToBack(rect); canvas.bringToFront(pug); canvas.add(rect); canvas.add(pug); canvas.renderAll(); }; pugImg.src = imgURL; canvas.on('object:scaling', function(e) { var bounds = e.target.getBoundingRect(); pug.set({ width: bounds.width, height: bounds.height, top: bounds.top, left: bounds.left }) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.2.0/fabric.js"></script> <canvas id="canvas" width=400 height=400></canvas>

I added image and one rectangle same size of image我添加了图像和一个相同大小的图像的矩形

In your example the rectangle is not the same size as the image在您的示例中,矩形与图像的大小不同

rect = {
  width: 150,
  height: 150,
  scaleX: 1,
  scaleY: 1,
}
pug = {
    width: 500,
    height: 500,
    scaleX: .25,
    scaleY: .25
});

To achieve the desired effect, you need to give theme the same (width, height, scaleX, scaleY), then just copy the rect (scaleX, scaleY) to the pug.为了达到想要的效果,你需要给主题相同(宽度,高度,scaleX,scaleY),然后只需将rect (scaleX,scaleY)复制到哈巴狗。 otherwise if they're not the same size you'll need to compute the scale ratio between the two.否则,如果它们的大小不同,则需要计算两者之间的比例。

 var imgURL = 'http://i.imgur.com/8rmMZI3.jpg'; var canvas = new fabric.Canvas('canvas'); var pug, rect; var pugImg = new Image(); pugImg.onload = function (img) { pug = new fabric.Image(pugImg, { angle: 0, width: 500, height: 500, left: 50, top: 70, scaleX: .25, scaleY: .25, selectable: false }); rect = new fabric.Rect({ top: 65, left: 200, width: 500, height: 500, scaleX: .25, scaleY: .25, fill: 'red', }); canvas.sendToBack(rect); canvas.bringToFront(pug); canvas.add(rect); canvas.add(pug); canvas.renderAll(); }; pugImg.src = imgURL; canvas.on('object:scaling', function(e) { pug.set({ scaleX: rect.scaleX, scaleY: rect.scaleY, }) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.2.0/fabric.js"></script> <canvas id="canvas" width=400 height=400></canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM