I would like to expand and update my collection of posts on canvas here, but maybe I should also do the same for my vuejs content also. So for today maybe it would be a smart move to write a post on using vuejs, and canvas elements. Oddly enough that is a rock i have not flipped over just yet. I really like vuejs a lot compared to other modern front end frameworks, and I sure like canvas a whole lot to, so lets get to some examples where we are combining two totally awesome things lime peanut butter and chocolate.
This basic example of canvas and vuejs involves just mounting to a single container div, and having a single canvas element as the template. In the template I am using the vue bind directive to bind width and height properties in the vue data object. I then have a single mounted life cycle hook that will draw to the canvas when the vue instance is mounted to the container element.
So far so good that canvas ends up being the logical pixel resolution I set in the data object as expected. However what if I where to change that resolution? Doing so might work but I would need to redraw what I worked out in the mounted hook. Still this is a simple starting point, so lets progress into something more advanced.
So now I took the rendering logic that I first worked out in the mounted hook, and transfered it to its own method in the methods option object. I am now creating references to the canvas and 2d drawing context the mounted hook, but now calling my new draw method in the method object to draw the content. In addition I now also have my new updated life cycle hook that will call that draw method each time the state updates.
When I change the logical pixel resolution I get the desired behavior, the resolution changes, and the content I have will be drawn. So there is drawing to the canvas for the first time, and then there is drawing to the canvas whenever something changes in the data object. Now there is just starting out with some user input.
So now on top of the vue bind directive I am also now using the vue on directive to do some event attachment. I am using the same method for both mouse clicks, and touch start events. When it comes to maybe turning this into some kind of real project it would be something that would work well with that kind of treatment of both mouse and touch events.
The click method in the methods object is what is called for every mouse click and touch start event. I am using a ternary operator to address the differences between mouse and touch events where just the first touch object is what will be seen as an equivalent to a mouse click. The get bounding client rect of the target element which in this case is the canvas is what I used to offset the x and y values so that they are relative to the canvas element, and not the windows object of the browser.