简体   繁体   English

任何可用于设置相对于 canvas 中心点而不是 FabricJS 中的顶部和左侧的对象的选项

[英]Any options available to set objects relative to canvas center point instead of top and left in FabricJS

I have an issue on mobile orientation change.我有关于移动方向更改的问题。 When the orientation changes the canvas size adjust himself accordingly.当方向改变时,canvas 尺寸会相应地调整自己。 And objects in the canvas exist in the same position after orientation where they were before the orientation relatively the canvas left and top. canvas 中的对象在定向后存在于相同的 position 中,而它们在定向之前相对于 canvas 左侧和顶部。

It will be more clear in the image.在图像中会更加清晰。 在此处输入图像描述

I want to change the positions of the objects on window:resize relatively to the center of canvas instead of left and top.我想改变 window 上对象的位置:相对于 canvas 的中心而不是左和上调整大小。 Please help!请帮忙!

You can center the object on canvas with canvas.centerObject(object);您可以使用canvas.centerObject(object); . .

 var canvas = new fabric.Canvas('c'); var dia1 = new fabric.Circle({ radius: 12, left: 0, top: 0, originX: 'center', originY: 'center', fill: 'transparent', strokeWidth: 5, stroke: "red", width: 50, height: 50, }); var dia2 = new fabric.Circle({ radius: 5, left: 0, top: 0, originX: 'center', originY: 'center', fill: 'red', width: 50, height: 50, }); var targetEl = new fabric.Group([dia1, dia2], { originX: 'center', originY: 'center', }); //center object on canvas canvas.centerObject(targetEl); canvas.add(targetEl); canvas.renderAll(); //center on window resize $(window).resize(function() { canvas.centerObject(targetEl); canvas.renderAll(); });
 canvas { border: 1px solid #ccc; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.js"></script> <canvas id="c" width="600" height="300"></canvas>

you may need to set the object dimensions as follwing您可能需要设置 object 尺寸如下

const canvas = new fabric.Canvas('canvas');
// you can simply use 
canvas.viewportCenterObject(obj);
// or if you want to center manually
const centerObject = obj => {
  const center = canvas.getCenter();
  const zoom = canvas.getZoom();
  canvas.centerObject(obj);
  obj.set({
    left:  center.left / zoom - obj.width / 2,
    top:  center.top / zoom - obj.height / 2,
  });
  obj.setCoords();
  canvas.calcOffset();
  canvas.renderAll()
};

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

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