Home > OS >  How can I load a canvas inside a div with Vue?
How can I load a canvas inside a div with Vue?

Time:10-12

I am really new to Vue and for this project, I was trying to load canvas inside a div. If the canvas is loaded outside of a div it works correctly but I want to display a canvas if loadModal is true only. In this code I have used two canvas one is inside div and other one is outside of div. It loads canvas correctly outside of div only. Is there a way to load canvas inside div as well? Here is my code below on JsFiddle

JsFiddle Code = https://jsfiddle.net/ujjumaki/6vg7r9oy/9/

View

<div id="app">
  <button @click="runModal()">
  Click Me
  </button>
  <br><br>
  <div v-if="loadModal == true">
    <canvas id="myCanvas" width="200" height="100" style="border:3px solid #d3d3d3; color:red;">
    </canvas>
  </div>
  
   <!-- this one loads correctly -->
   <canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
</canvas>

</div>

Method

new Vue({
  el: "#app",
  data: {
    loadModal: false,
  },
  methods: {
    runModal(){
        this.loadModal = true;
      var c = document.getElementById("myCanvas");
      var ctx = c.getContext("2d");
      ctx.beginPath();
      ctx.arc(95, 50, 40, 0, 2 * Math.PI);
      ctx.stroke();
    }
  }
})

CodePudding user response:

Try with v-show and with class instead id, so you can select all divs:

new Vue({
  el: "#app",
  data: {
    loadModal: false,
  },
  methods: {
    runModal(){
        this.loadModal = true;
      const c = document.querySelectorAll("canvas");
      c.forEach(can => {
        let ctx = can.getContext("2d");
        ctx.beginPath();
        ctx.arc(95, 50, 40, 0, 2 * Math.PI);
        ctx.stroke();
      })
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}
#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}
li {
  margin: 8px 0;
}
h2 {
  font-weight: bold;
  margin-bottom: 15px;
}
del {
  color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="runModal()">
  Click Me
  </button>
  <br><br>
  <div v-show="loadModal == true">
    <canvas class="canvas" id="myCanvas" width="200" height="100" style="border:3px solid #d3d3d3; color:red;">
    </canvas>
  </div>
  <canvas class="canvas" id="myCanvas" width="200" height="100" style="border:3px solid #d3d3d3; color:red;">
  </canvas>
</div>

  • Related