This is a simple step-by-step tutorial on how to use the popular p5.js in Vue. First of all, you don’t include p5 in any script tag. You need to import it via npm.
npm i p5
I suggest you make a separate component for the canvas, as it will make things a lot cleaner.
In you App.vue file (or wherever you want your canvas to go):
<template>
<div id="app">
<Canvas />
</div>
</template>
<script>
import Canvas from '@/components/Canvas'
// Note: @ refers to the /src/ folder
export default {
name: 'App',
components: {
Canvas
}
}
</script>
<style></style>
Then create the Canvas.vue component:
<template>
<div id="canvas"></div>
</template>
<script>
import P5 from 'p5' // Package from npm
export default {
name: 'App',
mounted() {
const script = p5 => {
// These are your typical setup() and draw() methods
p5.setup = () => {
p5.createCanvas(window.innerWidth, window.innerHeight);
};
p5.draw = () => {
p5.clear();
p5.ellipse(p5.mouseX, p5.mouseY, 40, 40);
};
} // Attach the canvas to the div
const p5canvas = new P5(script, 'canvas');
},
}
</script>
<style></style>
You can access all of p5’s methods by adding p5.
(i.e. fill()
will become p5.fill()
). Call your own functions like this:
// In the draw function
p5.draw = () => {
p5.yourFunction();
}p5.yourFunction = () => {
p5.fill('#111111');
p5.noStroke();
p5.ellipse(p5.mouseX, p5.mouseY, 40, 40);
}
You can checkout the p5.js documentation for more references.