Custom component with canvas

Struggling to make the above work…
I have a form in which I add components to a column panel via code.
The custom component is a canvas generated through html with unique id.
I’d like each add_component to generate a new canvas with the new details of the canvas, but I’m having a hard time understanding if I should add something in the form or in the html or in both.
Any help much appreciated.

Hi @azm08, I’ve moved this to its own topic.

If you could share a little more about the problem you’re facing (code snippets and a clone link would be helpful) so that others can more easily jump in and give you some support.

Here is the link to the app (first try so hopefully it works):
https://anvil.works/build#clone:VU4JHUDG6VBGLCGI=FYVJBA6XTWHHGRITTIDITCVT
When you run it, you can see that the 2 graphs overlay each other, and are not side by side. Reading the other topics on the forum, I’m pretty sure the issue is with the canvas/chart id that is the same. I’m just not getting my head around how I can pass a different id per chart, so as to make as many as I want to.

here’s something you could do

since you create each chart in the form show event
why not also create the canvas in the form show event

<script>
  function buildChart(chart_type, datasets, labels) {
    var canvas = document.createElement("canvas");
    canvas.width = 300;
    canvas.height = 225;
    // this is the jquery html template
    this.append(canvas);
    var ctx = canvas.getContext("2d");
    ...
  }
</script>

You will also want to only call this method once and it may be useful to add a flag

  def __init__(self, **properties):
    self.init_components(**properties)
    self._initialized = False
    
  def form_show(self, **event_args):
    if not self._initialized:
      self.call_js('buildChart', self.chart_type, self.datasets, self.labels)
    self._intialized = True

To get the charts side by side

If you want to add the components in code then:

  • I’d recommend a different container - FlowPanel or GridPanel
    (Column Panels are less suited to complex layouts in code (other than one on top of the other) and more suited to complex layouts in the design view).

You could also add the charts to the ContentPanel in the design view
And then in the __init__ method of Form1 update the properties for each chart

Here’s a clone of both adding_components in code and using the design view
I’ve added some responsiveness to both versions so that they should wrap on tablets

https://anvil.works/build#clone:E7UY7XFP2GKGIH5V=YJRKITQI3FJT6NB5QHZ2D2I2

3 Likes

Brilliant ! This works just great.
Thanks a lot @stucork !

1 Like