Write to a Canvas element via directives with VueJS
by Mani Jagadeesan
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<body>
<div id="app">
<canvas width="300" height="150" style="border:1px solid #BBB;" v-insert-message="exampleContent"></canvas>
<input type="text" v-model="exampleContent" />
<span>{{ exampleContent }}</span>
</div>
</body>
JavaScript
new Vue({
el: '#app',
data: {
"exampleContent": "This is TEXT"
},
directives: {
insertMessage: function(canvasElement, binding) {
// Get canvas context
var ctx = canvasElement.getContext("2d");
// Clear the canvas
ctx.clearRect(0, 0, 300, 150);
// Insert stuff into canvas
ctx.fillStyle = "black";
ctx.font = "20px Georgia";
ctx.fillText(binding.value, 10, 50);
}
}
})