如何使用从随机客户端获取的图像更新我的背景图像 url

How can I update my backgroud image url by the image I got from random client

我正在尝试制作一个允许我的用户自定义我网站的整个背景的功能。所以我制作了一个图片上传表格,但我不知道下一步该怎么做才能处理我从用户那里得到的这张图片。存储此图像或图像的位置以及如何访问此图像并将此图像作为背景图像。下面是我的 html

<div class="crossfade">
  <figure></figure>
  <figure></figure>
  <figure></figure>
  <figure></figure>
  <figure></figure>
</div>

我使用css

制作动画
.crossfade figure {
  animation: imageAnimation 60s linear infinite 0s;
  backface-visibility: hidden;
  background-size: cover;
  background-position: center;
  color: transparent;
  height: 100%;
  width: 100%;
  left: 0px;
  opacity: 0;
  position: absolute;
  top: 0px;
  z-index: -1;
  margin: 0;
}

.crossfade > figure:nth-child(1) {
  background-image: url(../img/0.jpeg);
}

.crossfade > figure:nth-child(2) {
  animation-delay: 12s;
  background-image: url(../img/1.jpeg);
}
.crossfade > figure:nth-child(3) {
  animation-delay: 24s;
  background-image: url(../img/2.jpeg);
}
.crossfade > figure:nth-child(4) {
  animation-delay: 36s;
  background-image: url(../img/0.jpeg);
}
.crossfade > figure:nth-child(5) {
  animation-delay: 48s;
  background-image: url(../img/1.jpeg);
}

@keyframes imageAnimation {
  0% {
    animation-timing-function: ease-in;
    opacity: 0;
  }
  8% {
    animation-timing-function: ease-out;
    opacity: 1;
  }
  17% {
    opacity: 1;
  }
  45% {
    opacity: 0;
  }
  100% {
    opacity: 0;
  }
}

并通过表单从用户处获取图像

<form id="background-form" method="get">
  <div>
    <label for="custom-file" class="form-label">Choose Images to upload(jpg, jpeg, or png) up to 5MB</label>
      <input
        required
        type="file"
        class="form-control"
        id="custom-file"
        accept=".jpg, .jpeg, .png"
        multiple/>
  </div>
</form>

和javascript文件来处理提交

const submit = document.querySelector("form#background-form")

function handleSubmit() {
  //How should I access to the image I got from form 
  //I tried to access by using URL.createObjectURL(file) API but didn't work
  //Or is there a way to store this image in localstorage or sessionstorage?
  //If it is possible how can I access to the image URL? 

}

有一种方法可以根据您的需要使用本地和会话存储来存储您的图像并计算在内,localStorage 的大小限制为 5mb,用户可以在需要时增加限制,但是,只有少数浏览器支持这一点,但另一方面,sessionStorage 大小仅受系统内存限制。

要将图像保存在 localStorage 中,您可以执行以下操作。

const fileInput = document.querySelector('#fileInput');

更改输入时 - 选择图像或更改时,此函数执行

fileInput.addEventListener('change', function () {
    const reader = new FileReader(); -- read content of files

加载文件内容时

    reader.addEventListener('load', function () {

在本地存储中保存结果(图像)

        localStorage.setItem('image', reader.result)
    })

读取 blob 或文件的内容

    reader.readAsDataURL(this.files[0]);
})