缩小后适合 X 轴和 scaleXY 以保持 canvas 在中心
Fit X-axis and scaleXY to keep canvas in center after zooming out
我想使用 Konva js 完成以下任务:
1- 从数据库循环数据,然后在 canvas 上绘制组,组包含圆圈+文本
2- 当形状增加时,缩小以将它们保持在中间
我遇到的挑战:
- 当形状超过图层宽度时,我开始缩小,但我无法将它们保持在中间。
如何根据形状计算图层 x 轴以保持 canvas 居中?
我如何计算缩放以保持新形状的位置而不是缩小太多?
提前致谢
请查找:codesandbox
首先,我以前从未使用过Konva
,所以也许还有其他比这更简单的解决方案。
使用 getClientRect
舞台边界与其宽度和高度进行比较以找到正确的比例然后将其转换到中心。
const adjustStage = function (stage) {
let width = stage.width()
let height = stage.height()
let scaleX = stage.scaleX()
let scaleY = stage.scaleY()
let rect = stage.getClientRect()
// calculate scale to fit stage on each axis then choose the small one
let scale = Math.min(
width / rect.width,
height / rect.height
)
stage.scale({
x: scaleX * scale,
y: scaleY * scale
})
// get new scaled rect
rect = stage.getClientRect()
// calculate distance difference between two centers on each axis.
stage.move({
x: width / 2 - (rect.x + rect.width / 2),
y: height / 2 - (rect.y + rect.height / 2)
})
stage.draw()
}
结果here
我想使用 Konva js 完成以下任务:
1- 从数据库循环数据,然后在 canvas 上绘制组,组包含圆圈+文本
2- 当形状增加时,缩小以将它们保持在中间
我遇到的挑战:
- 当形状超过图层宽度时,我开始缩小,但我无法将它们保持在中间。
如何根据形状计算图层 x 轴以保持 canvas 居中?
我如何计算缩放以保持新形状的位置而不是缩小太多?
提前致谢
请查找:codesandbox
首先,我以前从未使用过Konva
,所以也许还有其他比这更简单的解决方案。
使用 getClientRect
舞台边界与其宽度和高度进行比较以找到正确的比例然后将其转换到中心。
const adjustStage = function (stage) {
let width = stage.width()
let height = stage.height()
let scaleX = stage.scaleX()
let scaleY = stage.scaleY()
let rect = stage.getClientRect()
// calculate scale to fit stage on each axis then choose the small one
let scale = Math.min(
width / rect.width,
height / rect.height
)
stage.scale({
x: scaleX * scale,
y: scaleY * scale
})
// get new scaled rect
rect = stage.getClientRect()
// calculate distance difference between two centers on each axis.
stage.move({
x: width / 2 - (rect.x + rect.width / 2),
y: height / 2 - (rect.y + rect.height / 2)
})
stage.draw()
}
结果here