通过JS添加到当前背景图片?

Add To The Current Background Image Via JS?

我在 Photoshop 中创建了分层图像。我想每秒将该图像的一层添加到 div 的背景中。这是我目前正在使用的代码,但它不起作用。感谢任何帮助。

import React, { useRef, useEffect } from 'react';

import img1 from '../../img/INTRO/1.png';
import img2 from '../../img/INTRO/2.png';
import img2 from '../../img/INTRO/3.png';

function IntroMain() {
    const imageDiv = useRef();

    useEffect(() => {
        let arrOfImages = new Array(),
            i = 0,
            interval = 700,
            currentBG;
        window.setTimeout(() => {
            console.log('set bg img now');
            imageDiv.current.style.backgroundImage = `url(${img3})`;
            imageDiv.current.style.backgroundSize = `cover`;
            currentBG = `url(${img1}), `;
        }, interval);
        window.setTimeout(() => {
            console.log('set bg 2 img now');
            imageDiv.current.style.backgroundImage = `url(${img2})`;
            imageDiv.current.style.backgroundSize = `cover, cover`;
        }, interval * 2);
    });

    return <div id="image-div" ref={imageDiv}></div>;
}

export default IntroMain;

要在 div 上设置多个背景图像,您可以使用 css 属性 background-image。看起来像:

background-image: url('/first/image.jpg'), url('second/image.jpg') ...;

您的应用程序可以将图像网址和显示状态保存在一个数组中,您可以通过用户交互或根据时间更新该数组。然后,您可以从要显示的图像 url 中动态构建 css 属性 值。示例应用程序:

const IMAGES = [
  // this could be real paths instead
  /* red */ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
  /* green */ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
  /* blue */ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
];

const Toggle = ({ layers, onToggle }) => {
  // this component is just for demonstration of dynamically toggling images
  return layers.map((layer, idx) => (
    <button
      key={layer.url}
      onClick={() => onToggle(idx)}
      style={{ background: layer.display ? `url(${layer.url})` : "none" }}
    >{`Toggle Layer ${idx}`}</button>
  ));
};

const Layers = () => {
  // we initialize the array from the image urls and set every layer to display: false
  const [layers, setLayers] = useState(() =>
    IMAGES.map(url => ({ url, display: false }))
  );

  // this method toggles the display state of the layer at idx
  const handleToggleLayer = idx =>
    setLayers(current =>
      current.map((layer, i) =>
        i === idx ? { ...layer, display: !layer.display } : layer
      )
    );

  return (
    <div>
      <Toggle layers={layers} onToggle={handleToggleLayer} />
      <div
        className="layers"
        style={{
          backgroundImage: layers
            .filter(layer => layer.display)
            .map(layer => `url(${layer.url})`)
            .join(", ")
        }}
      />
    </div>
  );
};

现场演示:

请注意,列出的第一张图片将在顶部(最前面)。

示例使用 template strings to wrap the image paths in url( ... ) and .join() 加入它们。