cetz-package / cetz

CeTZ: ein Typst Zeichenpaket - A library for drawing stuff with Typst.
https://cetz-package.github.io
GNU Lesser General Public License v3.0
893 stars 36 forks source link

coordinates in draw-node / tree seem wrong #204

Closed raphCode closed 1 year ago

raphCode commented 1 year ago

I noticed that the coordinate data (node.x, node.y) in the draw-node function of tree do not align with the actual coordinates of the node, except when the tree direction is set to "up". A short demo explains the issue better than words:

#import "@preview/cetz:0.1.1": canvas, draw, tree

#set page(width: auto, height: auto, margin: .5cm)

#let data = (
  [A], ([B], [C], [D]), ([E], [F])
)

#canvas(length: 1cm, {
  import draw: *

  set-style(content: (padding: .2),
    fill: gray.lighten(70%),
    stroke: gray.lighten(70%))

  tree.tree(data, spread: 2.5, grow: 1.5, draw-node: (node, _) => {
    circle((), radius: .45, stroke: none)
    content((), node.content)
    circle((node.x, node.y), radius: .2, fill: blue)  \\ <============== HERE
  }, draw-edge: (from, to, _) => {
    line((a: from, number: .6, abs: true, b: to),
         (a: to, number: .6, abs: true, b: from), mark: (end: ">"))
  }, name: "tree")
})

image

Is this intentional? I expected the blue circles to line up with the gray nodes.

johannes-wolf commented 1 year ago

This is “intentional”. You should not use the node's x/y coordinates, as they are not in canvas coordinates but in the tree's coordinate system.

Use the current coordinate by saving it as an anchor:

#import "@preview/cetz:0.1.1": canvas, draw, tree

#set page(width: auto, height: auto, margin: .5cm)

#let data = (
  [A], ([B], [C], [D]), ([E], [F])
)

#canvas(length: 1cm, {
  import draw: *

  set-style(content: (padding: .2),
    fill: gray.lighten(70%),
    stroke: gray.lighten(70%))

  tree.tree(data, spread: 2.5, grow: 1.5, draw-node: (node, _) => {
    anchor("current", ())
    circle("current", radius: .45, stroke: none)
    content("current", node.content)
    circle("current", radius: .2, fill: blue)
  }, draw-edge: (from, to, _) => {
    line((a: from, number: .6, abs: true, b: to),
         (a: to, number: .6, abs: true, b: from), mark: (end: ">"))
  }, name: "tree")
})