我正在使用vue设置ascii相机,我在尝试从模板访问画布时遇到了这个问题。在bootCanvas()
中,当我尝试使用this.context = this.$ref.canvas.getContext('2d')
访问画布时,即使我已在模板中声明它,我也会收到错误"Cannot read property 'canvas' of undefined"
我90%确定错误的原因是脚本在模板之前运行,但我对vue很新,所以我可能会错过一些非常明显的东西,这可能会根本不是问题
我的代码如下:
<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>
答案 0 :(得分:0)
v-else阻止了元素的渲染。