review of a quick UI prototype

I put together a very quick UI (button hover, button press) demo. From purely javascript perspective it's OK. However, I am trying to figure out if this the way I should proceed with creating UI elements within the canvas or if I am making way too much work for myself and there are better ways to accomplish this task. I am very new to P5 so would love some council from more experienced devs. Aware of p5.dom but looking to eventually implement a canvas-only UI solution.


  • edited August 2016

    ... if this the way I should proceed with creating UI elements within the canvas...

    If those GUI elements go beyond simple buttons, you should consider a more dedicated GUI library like for example "dat.GUI":

  • edited August 2016

    ... but looking to eventually implement a canvas-only UI solution.

    Just for a pale idea, some example w/ squares:

    You can check it out online too:

  • edited August 2016 Answer ✓

    Though you'd rather prefer not to, a p5.Element approach is more streamlined b/c we can setup individual event callbacks for each 1.

    The tricky part is the position() method. It needs to be offset based on createCanvas()'s x & y properties, so the p5.Element objects are confined inside it.

    A silly example where a createSlider() got its position() calculated so it's centered within the createCanvas():

    You can also watch it online below: :bz

  • Answer ✓

    @dima: for a GUI where you're likely to have many instances of the same object you should ideally be adding methods to the Object's prototype and not wrapping it inside the object. Your current implementation is therefore sub-optimal. See You don't know JS

    I'd personally choose to do complex GUI handling outside of the canvas and instead do it in the DOM (e.g. using dat.gui or similar as GoToLoop suggested (or even your own implementation)). It's very easy to style and manage GUI elements in the DOM - for instance you can potentially apply a simple hover effect to all buttons with an extra line of CSS and no additional JS code...

    I also suspect that from a performance perspective this will be more efficient since the browser is already optimised to handle events on DOM elements; whilst on the canvas you'd have to manage all event listeners in your own code.

  • @blindfish totally gotcha on the prototypal inheritance path. I just like encapsulation object notation for clarity. OK, maybe my own twisted definition of clarity. And yes, that did confuse things greatly. My bad.

    @gotoloop thank you for the example on Codepen. This clarifies a ton.

    Love the dot.gui lib!

    Still weighing pros and cons of canvas-based or DOM-based GUI system but now have much better understanding of my options. Thank you both once again!

Sign In or Register to comment.