Move block to center of current viewport

132 views
Skip to first unread message

Timo Josten

unread,
Nov 15, 2023, 5:44:00 PM11/15/23
to Blockly
Hello,

I am creating a new block on my workspace programmatically like this:

```
const block = Blockly.getMainWorkspace().newBlock("block-type-id")
block.initSvg()
block.render()
```

This works fine, but always seems to render the block at coordinate (0,0).

I would like to move the block to the center of the current viewport of my workspace instead, but seem to be unable to do so. Can someone please advise on how to do so?

Many thanks in advance,
Timo

Maribeth Moffatt

unread,
Nov 15, 2023, 8:15:56 PM11/15/23
to Blockly
Hello,

You have a couple of options:

- If this is the first block you're putting on the workspace (or you otherwise don't mind scrolling the workspace after creating this block), you can call centerOnBlock to center the workspace on the given block.
- You can use serialization to create the new block and include x/y coordinates in the data, instead of calling newBlock, initSvg, and render.
- You can call moveTo or moveBy to move the block after you create it.

To find the coordinates of the current viewport, you can use workspace.getMetricsManager(), and from there get any number of metrics you may desire, like the viewMetrics.

Best,
Maribeth

Timo Josten

unread,
Nov 16, 2023, 2:41:41 AM11/16/23
to Blockly
Dear Maribeth,

thank you for the swift and helpful response. 

For the record, I was able to solve my ask with the following code:

```
let workspace = Blockly.getMainWorkspace()
let block = workspace.newBlock(item.id)

let workspaceCoordinates = workspace.getMetricsManager().getViewMetrics(true)
let x = workspaceCoordinates.left + (workspaceCoordinates.width / 2)
let y = workspaceCoordinates.top + (workspaceCoordinates.height / 2)
let blockCoordinates = new Blockly.utils.Coordinate(xy)

block.initSvg()
block.render()
block.moveTo(blockCoordinates)
```

Works like a charm - thanks again!

Cheers,
Timo
Reply all
Reply to author
Forward
0 new messages