mahee-auffret/components/Brush.vue

132 lines
3.3 KiB
Vue

<template>
<div ref="canvasContainer" id="canvasContainer"></div>
</template>
<script>
import p5 from 'p5';
export default {
mounted() {
if (process.client) {
this.p5Instance = new p5(this.sketch, this.$refs.canvasContainer);
}
},
beforeDestroy() {
if (this.p5Instance) {
this.p5Instance.remove();
}
},
methods: {
sketch(p) {
let brushStrokes = [];
const fadingTime = 2000;
const brushDensity = 30;
const textureDensity = 2;
const brushSize = 4;
p.setup = () => {
p.createCanvas(p.windowWidth, p.windowHeight);
p.clear();
p.colorMode(p.HSL);
p.noStroke();
};
p.draw = () => {
p.clear();
for (let i = brushStrokes.length - 1; i >= 0; i--) {
let brushStroke = brushStrokes[i];
let elapsedTime = p.millis() - brushStroke.startTime;
if (elapsedTime > fadingTime) {
brushStrokes.splice(i, 1);
continue;
}
let isSwiperOpen;
let swipers = document.querySelectorAll('.swiper');
for (let swiper of swipers) {
if (swiper.style.opacity == 1) isSwiperOpen = true;
}
if (!isSwiperOpen) {
let alpha = p.map(elapsedTime, 0, fadingTime, 1, 0);
for (let j = 0; j < brushStroke.dots.length; j++) {
p.fill(
brushStroke.dots[j].color.h,
brushStroke.dots[j].color.s,
brushStroke.dots[j].color.l,
alpha);
p.ellipse(
brushStroke.dots[j].x,
brushStroke.dots[j].y,
brushStroke.dots[j].size,
brushStroke.dots[j].size
);
}
}
}
};
p.mouseMoved = () => {
let dots = [];
for (let j = 0; j < brushDensity; j++) {
let angle = p.random(p.TWO_PI);
let r = p.sqrt(p.pow(p.random(1), 2)) * gaussian(brushSize, 3);
let x = p.mouseX + r * p.cos(angle);
let y = p.mouseY + r * p.sin(angle);
dots.push({
x: x,
y: y,
size: p.random(1) * textureDensity,
color: {
h: 178,
s: 20,
l: constrainedGaussian(22, 10, 10, 100)
}
});
}
brushStrokes.push({
x: p.mouseX,
y: p.mouseY,
startTime: p.millis(),
dots: dots
});
}
function gaussian(mean, sd) {
let u1 = p.random();
let u2 = p.random();
let z0 = p.sqrt(-2.0 * p.log(u1)) * p.cos(p.TWO_PI * u2);
return z0 * sd + mean;
}
function constrainedGaussian(mean, sd, min, max) {
let value;
do {
value = gaussian(mean, sd);
} while (value < min || value > max);
return value;
}
}
},
}
</script>
<style scoped>
#canvasContainer {
pointer-events: none;
top: 0;
left: 0;
z-index: 2;
position: fixed;
width: 100vw;
height: 100vh;
}
</style>