So I'm following a post in stackoverflow Convert Text to Image using javascript but in vue Js. I can't seem to get this working, it's throwing me this error
serve.vue?bf12:27 Uncaught TypeError: Cannot read properties of null (reading 'getContext')
at eval (serve.vue?bf12:27:1)
at Object../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader-v16/dist/index.js?!./dev/serve.vue?vue&type=script&lang=js (app.js:997:1)
at __webpack_require__ (app.js:849:30)
at fn (app.js:151:20)
at eval (serve.vue?5c0c:1:1)
at Module../dev/serve.vue?vue&type=script&lang=js (app.js:962:1)
at __webpack_require__ (app.js:849:30)
at fn (app.js:151:20)
at eval (serve.vue?061e:1:1)
Here's my code, it's simple enough
<template>
<div id="app">
<canvas id="textCanvas" height="20" />
<img id="image" />
<br />
<textarea id="text" />
</div>
</template>
<script>
var tCtx = document.getElementById("textCanvas").getContext("2d"), //Hidden canvas
imageElem = document.getElementById("image");
document.getElementById("text").addEventListener(
"keyup",
function () {
tCtx.canvas.width = tCtx.measureText(this.value).width;
tCtx.fillText(this.value, 0, 10);
imageElem.src = tCtx.canvas.toDataURL();
console.log(imageElem.src);
},
false
);
</script>
CodePudding user response:
The rendering engine hasn't rendered the HTML at the point in time when you make the call to documents.getElementById('textCanvas')
.
In fact, to be honest, your code is hardly Vue at all. Vue has a lifetime hook called mounted
, which occurs when the rendering engine has finished rendering the component. In order to use this, you'd convert the code above to actual Vue.
Something akin to this:
<template>
<div id="app">
<canvas ref="canvas" height="20" />
<img id="image" />
<br />
<textarea @keyup="handleKeyUp" />
</div>
</template>
<script>
export default {
computed: {
canvas() {
return this.$refs.canvas;
};
},
methods: {
handleKeyUp() {
// Do your thing with "this.canvas"
}
}
}
</script>
I really suggest you to learn the basic concept and syntax of Vue, before venturing into something like this.
CodePudding user response:
You need to put all logic relates to DOM manipulation into mounted hook. See the demo https://codesandbox.io/s/red-flower-jwx6ew?file=/src/App.vue