2016-11-17 28 views
0

我使用vue設置了一個ascii相機,在嘗試從模板訪問畫布時遇到此問題。在bootCanvas()當我嘗試使用this.context = this.$ref.canvas.getContext('2d')訪問畫布我得到一個錯誤說"Cannot read property 'canvas' of undefined"即使我已經宣佈它在模板如何讓vue模板在腳本之前運行?

我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

v-其他正在阻止元素渲染。

+0

它最初是我的代碼中的$ refs。不知道它是如何在這裏被引用的。仍然無法正常工作。任何其他想法? –

+0

您是否使用Vue 1或2 – RDelorier

+0

我正在使用vue 2 –

相關問題