react-particles-js:无法设置背景和宽度

问题描述

我已经安装了 react-particles-js,一切正常,但现在我已经创建了一些自定义设计,并通过它的参数将其分配给粒子,就像这样:

<Particles
          params={{
            particles: {
              number: { value: 35,density: { enable: true,value_area: 800 } },color: {
                value: [
                  'BB4D10','#820E42','#BD740F','#248592','#5F4DAF','#8BA00F',],},shape: {
                type: 'circle',stroke: { width: 0,color: '#000000' },polygon: { nb_sides: 3 },image: { src: 'img/github.svg',width: 100,height: 100 },opacity: {
                value: 1.5,random: false,anim: {
                  enable: false,speed: 1,opacity_min: 0.1,sync: false,size: {
                value: 9,random: true,speed: 43.15684315684316,size_min: 0.1,line_linked: {
                enable: true,distance: 100.82952832645452,color: '#ffffff',opacity: 1.4,width: 1,move: {
                enable: true,speed: 2,direction: 'none',straight: false,out_mode: 'out',bounce: false,attract: { enable: false,rotateX: 600,rotateY: 1200 },interactivity: {
              detect_on: 'canvas',events: {
                onhover: { enable: true,mode: 'bubble' },onclick: { enable: false,mode: 'push' },resize: true,modes: {
                grab: { distance: 400,line_linked: { opacity: 1 } },bubble: {
                  distance: 109.63042366068159,size: 13,duration: 2,opacity: 8,speed: 3,repulse: { distance: 200,duration: 0.4 },push: { particles_nb: 4 },remove: { particles_nb: 2 },retina_detect: true,}}
          style={styling}
        />

在那之后,我尝试添加背景颜色以使其看起来正确,但正如我所看到的,我尝试传递给粒子的样式不起作用,至少该位置适用。

const styling = {
  backgroundColor: '#2a2e31',position: 'absolute',width: '10%',};

This is how it looks without the background color and width

解决方法

有几种方法可以控制样式:

  1. 您可以为画布包装器提供 className 道具,为画布宽度提供 width 道具:
<Particles
  ...
  style={styling}
  width="10%"
  className="particles-wrapper"
/>

然后,编写 CSS:

.particles-wrapper {
  background-color: #2a2e31;
  height: 100%;
  width: 10%; // You may need this or may not depending on your requirement
}
  1. 或者,您可以添加一个新的 div,它将包裹 <Particles .. /> 并将此 div 的样式设置为默认情况下 canvas 是透明的。

  2. 或者,您可以使用 canvasClassName 属性并设置此类的样式。

这是使用上述第一种方法后的快照:

canvas


我们需要分别传递 widthheight 的原因是,如 source code 中所见,props.style 中的那些被覆盖如下:

style={{
  ...this.props.style,width,height
}}
,

为粒子设置背景的最简单方法是使用 background 选项。

<Particles params={{
  background: {
    color: "#000"
  },/* all other options you set */
}} />

这将为画布设置背景。如果您需要透明的,请使用 @ajeet-shah 答案。