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
JavaScript
x
15
15
1
<div id="app">
2
<button @click="runModal()">
3
Click Me
4
</button>
5
<br><br>
6
<div v-if="loadModal == true">
7
<canvas id="myCanvas" width="200" height="100" style="border:3px solid #d3d3d3; color:red;">
8
</canvas>
9
</div>
10
11
<!-- this one loads correctly -->
12
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
13
</canvas>
14
</div>
15
Method
JavaScript
1
17
17
1
new Vue({
2
el: "#app",
3
data: {
4
loadModal: false,
5
},
6
methods: {
7
runModal(){
8
this.loadModal = true;
9
var c = document.getElementById("myCanvas");
10
var ctx = c.getContext("2d");
11
ctx.beginPath();
12
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
13
ctx.stroke();
14
}
15
}
16
})
17
Advertisement
Answer
Try with v-show
and with class instead id, so you can select all divs:
JavaScript
1
21
21
1
new Vue({
2
el: "#app",
3
data: {
4
loadModal: false,
5
},
6
methods: {
7
runModal(){
8
this.loadModal = true;
9
const c = document.querySelectorAll("canvas");
10
c.forEach(can => {
11
let ctx = can.getContext("2d");
12
ctx.beginPath();
13
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
14
ctx.stroke();
15
})
16
}
17
}
18
})
19
20
Vue.config.productionTip = false
21
Vue.config.devtools = false
JavaScript
1
21
21
1
body {
2
background: #20262E;
3
padding: 20px;
4
font-family: Helvetica;
5
}
6
#app {
7
background: #fff;
8
border-radius: 4px;
9
padding: 20px;
10
transition: all 0.2s;
11
}
12
li {
13
margin: 8px 0;
14
}
15
h2 {
16
font-weight: bold;
17
margin-bottom: 15px;
18
}
19
del {
20
color: rgba(0, 0, 0, 0.3);
21
}
JavaScript
1
13
13
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
2
<div id="app">
3
<button @click="runModal()">
4
Click Me
5
</button>
6
<br><br>
7
<div v-show="loadModal == true">
8
<canvas class="canvas" id="myCanvas" width="200" height="100" style="border:3px solid #d3d3d3; color:red;">
9
</canvas>
10
</div>
11
<canvas class="canvas" id="myCanvas" width="200" height="100" style="border:3px solid #d3d3d3; color:red;">
12
</canvas>
13
</div>