Drawing onto a canvas with vue.js

后端 未结 3 1752
情深已故
情深已故 2020-12-28 16:08

I don\'t think this is necessarily a Vue based issue, but I\'m running into some trouble.

I\'d like to write to the canvas a Vue variable. If I remove vue, my initia

3条回答
  •  攒了一身酷
    2020-12-28 16:20

    Please check this jsFiddle: https://jsfiddle.net/mani04/r4mbh6nu/

    EDIT: updated with dynamic text: https://jsfiddle.net/mani04/r4mbh6nu/1/

    In the above example, I am able to write into canvas, and also ensure that the input text goes into span as you would expect, all using Vue.js

    Coming back to your example, the HTML is:

    {{ exampleContent }}

    Vue.js reads the elements inside #app and keeps it as the template for your Vue app. So your canvas, input and span elements will now be re-rendered by Vue.js when it constructs the DOM.

    During this process, your original canvas text - the one you set before initiating the Vue application gets lost.

    There is no clear way to solve this issue other than using a directive, as in my jsFiddle example. A Vue directive helps you capture the DOM element.

    In my example, I define a Vue directive called insert-message which I use on canvas as v-insert-message. This allows me to capture the DOM element and then do the other steps: getContext and fillText. There is no id required, or no javascript code to getElementById.

    One more thing - your canvas is just too large, and therefore you were not able to see your input and span elements. They were working normally in your example also!

    EDIT: example for directive bindings

    I just found a way to use directives and still write dynamic stuff into canvas.

    Check the updated jsFiddle: https://jsfiddle.net/mani04/r4mbh6nu/1/

提交回复
热议问题