I'm trying to implement dark mode on my web where I have the particlesj script and I need to modify the color of the particles for the light mode. Is there any way to switch between JSON files? Let's say particles.json and particles-light.json. Appreciate any help so much.
CodePudding user response:
In the GitHub reop you can find the following example:
particlesJS.load('particles-js', 'assets/particles.json', function() {
console.log('callback - particles.js config loaded');
});
I guess that you can probably call this load() function with a new JSON file when needed.
CodePudding user response:
Alright so I've been trying and finally came to a solution. What I've done is to create a function associated to the theme selector checkbox.
particlesJS.load('particles-js', 'assets/particles.json');
function ThemeSwitch() {
if (document.getElementById('checkbox').value === 'dark') {
particlesJS.load('particles-js', 'assets/particles-light.json');
document.getElementById('checkbox').value = 'light';
} else {
particlesJS.load('particles-js', 'assets/particles.json');
document.getElementById('checkbox').value = 'dark';
}
}
And this is the input.
<input type="checkbox" id="checkbox" name="check" value="dark" onclick="ThemeSwitch()"/>
Good or bad (have no JS idea pretty much), it is working.
CodePudding user response:
I've made a sample using themes with tsParticles here: https://codepen.io/matteobruni/pen/vYejMNr
You can have a single config with configured themes like in the sample above.
I'll show below more in details how to achieve it.
// the particles container, used for calling the loadTheme method
let themeableContainer;
document.getElementById("btnLight").addEventListener("click", () => {
if (themeableContainer) {
// the theme name must be used when loading theme
themeableContainer.loadTheme("light");
}
});
document.getElementById("btnDark").addEventListener("click", () => {
if (themeableContainer) {
// the theme name must be used when loading theme
themeableContainer.loadTheme("dark");
}
});
tsParticles.loadJSON("tsparticles", "particles.json").then((container) => {
// assigning the loaded container
themeableContainer = container;
});
and the config looks like this
{
"fpsLimit":60,
"particles":{
"move":{
"bounce":false,
"direction":"none",
"enable":true,
"outModes":"out",
"random":false,
"speed":2,
"straight":false
},
"number":{
"density":{
"enable":true,
"area":800
},
"value":80
},
"opacity":{
"value":0.5
},
"shape":{
"type":"circle"
},
"size":{
"value":{
"min":1,
"max":5
}
}
},
"themes":[
{
"name":"light",
"default":{
"value":true,
"mode":"light"
},
"options":{
"background":{
"color":"#fff"
},
"particles":{
"color":{
"value":"#000"
}
}
}
},
{
"name":"dark",
"default":{
"value":true,
"mode":"dark"
},
"options":{
"background":{
"color":"#000"
},
"particles":{
"color":{
"value":"#fff"
}
}
}
}
]
}
The theme object accept those values, the options inside are a whole options so you can override everything from the background to the particles options.
