How to export Cetz diagrams in HTML?

With the new experimental HTML exporter, is there a way to export Cetz diagrams? Currently if I compile a document

#import "@preview/cetz:0.3.2"
//#set page(width: auto, height: auto, margin: .5cm)

#show math.equation: block.with(fill: white, inset: 1pt)

#cetz.canvas(length: 3cm, {
 ...
})

with typst compile --features html --format html ..., I get

warning: block was ignored during HTML export
    ┌─ @preview/cetz:0.3.2/src/canvas.typ:18:90

I don’t see this explicitly mentioned on the roadmap for HTML, so I wonder if there is a way to do it. This would be very helpful for preparing lecture slides.

I haven’t used it myself yet, but that’s what this function is for:

It designates part of the document as something that should use the regular Typst layouting. The result is included as an SVG image.

Like #html.frame(cetz.canvas(...))?

Yes, here’s a complete example:

#import "@preview/cetz:0.3.2"

#show figure.where(kind: "cetz"): it => {
  if target() == "html" { html.frame(it) } else { it }
}

#let drawing(..args) = figure(
  kind: "cetz",
  supplement: none,
  cetz.canvas(..args),
)

#drawing(length: 3cm, {
  import cetz.draw:* 
  line((0, 0), (1, 1))
  line((1, 0), (0, 1))
})

hmm, I’m not sure I’d do it like that. If I’m not mistaken, that would include the caption in the frame and thus make it part of the SVG image (not selectable, at least in most browsers, and inconsistent with non-cetz figures). – oh! I just noticed that actually doesn’t allow you to add a caption since all args are passed to CeTZ.

Also, the custom kind could lead to outline problems if the cetz drawing should be a regular image (or some other existing kind).

I would rather define a wrapper function:

#import "@preview/cetz:0.3.2"

#let drawing(..args) = {
  let canvas = cetz.canvas(..args)
  context if target() == "html" {
    html.frame(canvas)
  } else {
    canvas
  }
}

#figure(
  drawing(length: 3cm, {
    import cetz.draw:* 
    line((0, 0), (1, 1))
    line((1, 0), (0, 1))
  }),
)

Then you can still configure the figure element however it’s necessary. The only downside is that drawing is opaque due to context.

1 Like

Here I use figure as a poor man’s custom type, so that cetz diagrams can be easily queried and configured with show rules. It’s not meant to include a caption. If the user wants the diagram in an actual figure, they’re expected to write figure(drawing(...), caption: ...). But I also like your version, it’s a simpler example.

1 Like

Hey @Chrysoberyl, welcome to the forum! I’ve changed your question post’s title to better fit our guidelines: How to post in the Questions category

For future posts, make sure your title is a question you’d ask to a friend about Typst. :wink:

1 Like