所以我正在關注stackoverflow Convert Text to Image using javascript但在 vue Js 中的帖子。我似乎無法讓它作業,它給我這個錯誤
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)
這是我的代碼,很簡單
<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>
uj5u.com熱心網友回復:
在您呼叫documents.getElementById('textCanvas').
事實上,說實話,你的代碼根本就不是 Vue。Vue 有一個名為 的生命周期鉤子mounted,它在渲染引擎完成渲染組件時發生。為了使用它,您需要將上面的代碼轉換為實際的 Vue。
類似于這樣的東西:
<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>
我真的建議你在嘗試這樣的事情之前學習 Vue 的基本概念和語法。
uj5u.com熱心網友回復:
您需要將所有與 DOM 操作相關的邏輯放入掛載的鉤子中。查看演示https://codesandbox.io/s/red-flower-jwx6ew?file=/src/App.vue
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/480976.html
