I'm currently implementing p5js in VueJS but got some complications at getting variables. My code snippet is:
<template>
<div style="margin-top: 72px;">
<b-container>
<div ref="canvas"></div>
<b-btn>Change color</b-btn>
</b-container>
</div>
</template>
<script>
export default {
data: function () {
return {
script: null,
ps: null
}
},
mounted () {
this.script = p => {
var x = 100
var y = 100
var canvas = null
p.setup = _ => {
canvas = p.createCanvas(600, 420)
canvas.parent(this.$refs.canvas)
p.frameRate(60)
}
p.draw = _ => {
p.background(0)
p.fill(255)
p.rect(x, y, 50, 50)
}
}
const P5 = require('p5')
this.ps = new P5(this.script)
console.log(this.ps)
}
}
</script>
It renders perfectly and works, but is there any possibility to get the variables like x, y, canvas so that I can update my DOM in VueJS (with the data component) accordingly? Thanks
Why don't you do something like this. I'm assuming that you require x, y and canvas in the data object used by VueJS.
<template>
<div style="margin-top: 72px;">
<b-container>
<div ref="canvas"></div>
<b-btn>Change color</b-btn>
</b-container>
</div>
</template>
<script>
export default {
data: function () {
return {
script: null,
ps: null,
x: 0,
y: 0,
canvas: null
}
},
mounted () {
this.script = p => {
this.x = 100
this.y = 100
p.setup = _ => {
this.canvas = p.createCanvas(600, 420)
this.canvas.parent(this.$refs.canvas)
p.frameRate(60)
}
p.draw = _ => {
p.background(0)
p.fill(255)
p.rect(this.x, this.y, 50, 50)
}
}
const P5 = require('p5')
this.ps = new P5(this.script)
console.log(this.ps)
}
}
</script>
This should work
As @Rud156 mentioned, any variables that you want the vue component to have access to should be defined in the component first (as data, computed, props, etc), you can then access it and modify it if required in your p5.js sketch. Variables defined only in the sketch will stay private the the sketch.
Questions regarding your own code are best posted on the forum, github issues are usually for bug reports or feature requests. Thanks!
Thank you,
sorry for posting an issue. Next time I'll try the forums!
Most helpful comment
Why don't you do something like this. I'm assuming that you require
x, y and canvasin the data object used by VueJS.This should work