DEV Community

Cover image for Draw Canvas with JSX (or XML)
Athaariq Ardhiansyah
Athaariq Ardhiansyah

Posted on


Draw Canvas with JSX (or XML)

Hi folks!

I just figured out how to draw something on canvas almost like composing HTML DOM.

Why is this matter?

Well... let's see the comparison

Draw a single blue square

a single blue square on the browser

...and This is how it's made

Code to make blue square on the browser

Okay but what's the point? It didn't proof anything aside preventing canvas stretch issue!

Good question. Now see the real use case:

Draw complex shapes

Ben 10 knock-off logo

Did you see that green circle logo? This is how you make it with canvas

Code to make Ben 10 knock-off logo

Wow massive difference. But how we compose it programmatically without hurting performance much? Should we ditch Compodraw for that case?

Not necessarily, you can compose existing instructs by hands and let them handle context scoping + geometrical math stuffs. So you just focus on your logic. Here's the example:

Programmatical Composition

Group of squares that gradually turn white

Did you see the shadow? you don't have to configure shadow manually. Instead, let Elevate instruct handle those rectangles' shadow. Here's the code:

Code of programmatical composition

Okay, "instruct" words just being written repeatedly. But what's the meaning of that?

Instruct is just a bunch of instruction for drawing (or giving effect to) shape. Imagine of having a lot of snippet for doing such thing and all you need to do is just use them and set properties for them. Then they will draw the shapes for you.

Instructs are modular. That means people can create their own a package of instructs and share it to community.

Here's the example of a package of instructs.

I want to try, how do I start?

On compodraw github repo, there is an installation procedure you can follow + some examples.

I hope this tool can help your project, happy hacking!

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await