简体   繁体   English

如何在 Fabric.js 中获取当前视图的中心坐标?

[英]How to get the center coordinates for current view in Fabric.js?

I am working on a image loading system and for it to work on mobile, I need to get coordinates of the center of canvas for my current view.我正在开发一个图像加载系统,为了让它在移动设备上工作,我需要为我当前的视图获取 canvas 中心的坐标。 It should return the same result as if I mouse over the center.它应该返回与我将鼠标悬停在中心上相同的结果。

I tried asking on fabric js github and they gave me this: but that result gave me back half my canvas height and width every time.我尝试询问织物 js github,他们给了我这个:但结果每次都给了我一半的 canvas 高度和宽度。 can anyone help me understand why?谁能帮我理解为什么?

var myCenterCoordinates = fabric.util.transformPoint({
  x: canvas.width / 2,
  y: canvas.height / 2,
}, fabric.util.invertTransform(canvas.viewportTransform));

If i mouse over the exact center of the canvas(i do have mouse position set up), I should see the same result of(x and y) if i call getcentercoordinates function如果我将鼠标悬停在画布的确切中心(我确实设置了鼠标 position),如果我调用 getcentercoordinates function,我应该看到相同的结果(x 和 y)

edit: fabric.util.invertTransform(canvas.viewportTransform)[4] and fabric.util.invertTransform(canvas.viewportTransform)[5] gives you your current x and y coodinates for top left corner of your current view point, so we might be able to do something with that strong text编辑: fabric.util.invertTransform(canvas.viewportTransform)[4] 和 fabric.util.invertTransform(canvas.viewportTransform)[5] 为您提供当前视点左上角的当前 x 和 y 坐标,因此我们可能能够用那个强大的文本做点什么

I found the answer:我找到了答案:

var zoom=canvas.getZoom()
function CenterCoord(){
   return{
      x:fabric.util.invertTransform(canvas.viewportTransform)[4]+(canvas.width/zoom)/2,
      y:fabric.util.invertTransform(canvas.viewportTransform)[5]+(canvas.height/zoom)/2
   }
}

to use this:使用这个:

var centerX=CenterCoord().x
var centerY=CenterCoord().y

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

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