![](/img/trans.png)
[英]How can I run condition in vue component before run html in the template?
[英]How to get vue template to run before script?
我正在使用vue設置ascii相機,在嘗試從模板訪問畫布時遇到了這個問題。 在bootCanvas()
當我嘗試使用this.context = this.$ref.canvas.getContext('2d')
"Cannot read property 'canvas' of undefined"
即使我聲明了"Cannot read property 'canvas' of undefined"
也會收到錯誤消息它在模板中
我90%確信錯誤的原因是腳本在模板之前運行,但是我很陌生,所以我可能在這里遺漏了很明顯的東西,而這可能根本不是問題
我的代碼如下:
<template>
<div v-if="error === null">
<p v-if = "stream === null">
Please allow acces to your camera when prompted
</p>
<p v-else>
<video class="video" v-bind:src="stream" ref:video autoplay></video>
<canvas class="canvas" ref:canvas ></canvas>
</p>
</div>
<div v-else>
{{ error }}
</div>
</template>
<script>
export default {
data () {
return {
//where out errors will be held
error: null,
//where our stream will be held
stream: null,
//for html canvas
context: null,
//ascii options
ascii: {
contrast: 30,
fps: 30
}
}
},
methods: {
//access webcam
initVideo () {
navigator.getUserMedia({
//we want video but not audio
video: true,
audio: false
}, (stream) => {
//get the webcam stream
this.stream = window.URL.createObjectURL(stream)
this.bootCanvas().then(() => {
this.startAsciiRendering()
})
//throw error if failed
}, this.setError)
},
startAsciiRendering () {
setInterval(() => {
alert('run')
// console.log('run')
}, Math.round(1000 / this.ascii.fps))
},
bootCanvas () {
return new Promise((resolve, reject) => {
this.context = this.$ref.canvas.getContext('2d')
//video dimensions
this.$refs.canvas.width = 200
this.$refs.canvas.height = 150
})
resolve()
},
//errors
setUnsupported () {
this.error = 'Your browser does not support video :(';
},
setError () {
this.error = 'Something went wrong, try refreshing the page';
}
},
//mounted = when page loads
mounted () {
//check if able to get webcam
if (navigator.getUserMedia) {
this.initVideo()
} else {
this.setUnsupported()
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="sass">
html, body
width: 100%
height: 100%
margin: 0
padding: 0
.video
width: 200px
position: fixed
top: 0
left: 0
z-index: 1
</style>
v-else阻止了元素的渲染。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.