What is the best way to ensure that the vue template runs before the script?

While attempting to set up an ASCII camera using Vue, I encountered a problem trying to access the canvas from the template. In the bootCanvas() method, when attempting to access the canvas with

this.context = this.$ref.canvas.getContext('2d')
, an error is thrown stating
"Cannot read property 'canvas' of undefined"
, despite being declared in the template.

I suspect that the error may be due to the script running before the template, but as a newbie to Vue, I could be overlooking something obvious and this might not be the actual cause.

Here's my code:

<template>
    <div v-if="error === null">
     <p v-if = "stream === null">
       Please allow access 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 our errors will be stored
      error: null,
      //where our stream will be stored
      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>

Answer №1

The use of v-else was causing the element to not render properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on retrieving the value of a dynamically created control in ASP.NET c# prior to page loading

Is there a way to retrieve the value of a dynamically created control before the page loads in ASP.NET using C#? protected void Page_PreInit(object sender, EventArgs e) { int i = 0; //createDynamicControl(i); var elems = Request.Form.AllKeys.W ...

Dynamic classroom experience featuring a bootstrap sidebar

I am having an issue with changing the active class of the sidebar after a click event. I have tried using Bootstrap and implemented some JavaScript code, but it doesn't seem to be working properly. $(function(){ $('.sidebar1 a').filt ...

Tips for displaying the selectpicker once it is fully loaded

My webpage features a select element styled with the selectpicker plugin. However, upon loading the page, there is a brief period where the select area looks subpar. How can I ensure that the select is displayed only after it has been fully rendered by the ...

Using react-big-calendar exclusively for the month view

I need help customizing react-big-calendar to only show the month view and trigger a function when a date is selected. I want to remove all other functionalities related to week, day, agenda, and time display. Essentially, I just want to display the month- ...

angularjs controller module reference results in a page that fails to load

I am currently in the process of integrating the angular-wizard module into my Angular application. The Angular app was generated using yeoman. I installed the angular-wizard module using bower install angular-wizard and added it to my index.html file jus ...

Stop jQuery Tab from Initiating Transition Effect on Current Tab

Currently, I am utilizing jQuery tabs that have a slide effect whenever you click on them. My query is: How can one prevent the slide effect from occurring on the active tab if it is clicked again? Below is the snippet of my jQUery code: $(document).read ...

Sails.js encounters issues initializing Passport.js when SSL is implemented

Currently utilizing Sails.js (v0.9.4) and passport(local strategy) with no issues. The need arises to configure Sails.js behind SSL. Therefore, the setup includes: (Port 8080 selected for SSL). Upon starting Sails, it responds correctly, except for those ...

Error: Unable to locate the Vue editor JS module

Currently, I am integrating VUE JS into Laravel and would like to incorporate a block editor using this package. I have included the import statement as follows: import Editor from 'vue-editor-js'. However, upon running the command npm run dev, i ...

I am looking to obtain a value through a JavaScript function that sums values upon clicking. The result is satisfactory, but I am seeking a way to limit the value

I only need 2 decimal values, not large ones. Can someone please help me achieve this? <script> $(function() { $("#isum, #num1, #num2, #num3, #rec1, #rec2, #rec3, #difnum1, #difnum2, #difnum3").on("keydown ke ...

Using the arrow keys, I must adjust the border sides

I am looking to switch between different sides of borders by using the arrow keys $(function(){ $(document).keydown(function(e){ switch(e.which){ case 38:$("#sh").css("border-top-color", "#fff"); //arrow up break; ...

What is the best way to enforce a required bindings property in an AngularJS component?

Suppose I have the following component defined: angular.module('myApp').component('myComponent', { templateUrl: 'myComponent.html', bindings: { myPropOne: '<', myPropTwo: '<' ...

Is there a way to ensure that introjs follows the structure of slides effectively?

I created a modal that features multiple slides, each containing its own form. <v-bottom-sheet v-model="showCreateRecordModal" inset max-width="600px" class="rounded-t-xl" scrollable persistent> <v-card v-if=&quo ...

Is there a way to confirm the presence of multiple attributes in a JSON format using JavaScript?

Currently, I am developing a module that processes multiple complex JSON files and requires a method to notify users if certain elements are missing. Although the current approach works, I can't shake the feeling that there must be a more efficient a ...

Transmitting JSON information using post method through .ajax(), as well as receiving a JSON reply

Seeking assistance with debugging a registration page I am currently coding. I have hit a roadblock for the past 48 hours and would greatly appreciate any help in resolving the issues. CHALLENGE I am utilizing JavaScript to validate form inputs for error ...

css clip-path hover effect restricted to specific shape

In the codepen I created, there are two greyscaled shapes. Currently, it's only possible to hover over one of them, as the original size is a box that overlaps both images. Is there a way to detect the shape being hovered over? Z-index hasn't pro ...

What are some strategies for bypassing the restrictions on Cross Origin Requests?

I am currently facing an issue with retrieving a file from the server where my PHP code is hosted, which is a web hosting service. This problem is not unfamiliar to me as I have previously encountered difficulties accessing files from HTML, whether locall ...

"AngularJS View Source Page: Unveiling the Power of Dynamic Metatags

Hey there, I have a requirement where I need to update the metatags content dynamically. I successfully updated the content in INSPECT ELEMENT, but I am unable to see the updated content in the view source page. I want to update the metatags in the view ...

MongoDB is experiencing an issue where the latest document is not being stored at the

Storing comments for my webpage in MongoDB has been flawless so far. Whenever a new comment is saved, it gets added to the bottom of the collection. This results in the newest comment appearing at the top when loading comments, which is ideal. However, I e ...

What is the best way to make a container 100% tall and display a navigation bar?

Struggling to properly render my React page This is what I have: ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router /> </Provider> </React.StrictMode>, document.getEl ...

Create object keys without relying on any ORM or database management systems like mongoose or mongodb

Exploring a Mongoose Object: recipe = { "ingredients": [ { "_id": "5fc8b729c47c6f38b472078a", "ingredient": { "unit": "ml", "name" ...