有没有一种方法可以在JavaScript中创建一个函数,它可以保存3个或更多的svg或png,并将其作为gif或视频播放?

798qvoo8  于 2023-04-19  发布在  Java
关注(0)|答案(1)|浏览(105)

我有一系列的方块,我可以填充不同的颜色到每个方块,并将其保存在背景中的PNG格式。当用户点击下一步,它应该播放视频与这些系列不同颜色的方块作为预览。
请帮我解决这个问题。下面的JS代码不能播放GIF。

function saveSquaresAsPng() {
    // Get all square elements
    const squares = document.querySelectorAll(".square");

    // Loop through squares and save as PNG
    for (let i = 0; i < squares.length; i++) {
        const square = squares[i];

        html2canvas(square).then(canvas => {
            // Convert canvas to PNG data URL
            const pngDataUrl = canvas.toDataURL("image/png");

            // Create a link to download the PNG file
            const link = document.createElement("a");
            link.download = `square-${i + 1}.png`;
            link.href = `"./images/square-" + (i + 1) + ".png"`;
            link.click();
        });
    }
}

function createGif() {
    // Get all saved PNGs and add them to the gif
    const gif = new GIF({
        workers: 2,
        quality: 10,
        width: 300,
        height: 300
    });
    for (let i = 1; i <= 3; i++) {
        const img = new Image();
        img.src = `"./images/square-" + i + ".png"`;
        gif.addFrame(img);
    }

     // Render the GIF and set it as the source of the <img> tag
     gif.on('finished', function(blob) {
        const imgTag = document.getElementById("myGif");
        imgTag.src = URL.createObjectURL(blob);
    });

     // Render frames into an animated GIF
    gif.render();

    console.log(gif);
}

我希望保存方块并以gif格式播放。

von4xj4u

von4xj4u1#

试试下面的代码:

function saveSquaresAsPng() {
  // Get all square elements
  const squares = document.querySelectorAll(".square");

  // Loop through squares and save as PNG
  for (let i = 0; i < squares.length; i++) {
    const square = squares[i];

    html2canvas(square).then(canvas => {
      // Convert canvas to PNG data URL
      const pngDataUrl = canvas.toDataURL("image/png");

      // Create a link to download the PNG file
      const link = document.createElement("a");
      link.download = `square-${i + 1}.png`;
      link.href = `./images/square-${i + 1}.png`;
      link.click();
    });
  }
}

function createGif() {
  // Get all saved PNGs and add them to the gif
  const gif = new GIF({
    workers: 2,
    quality: 10,
    width: 300,
    height: 300
  });
  for (let i = 1; i <= 3; i++) {
    const img = new Image();
    img.src = `./images/square-${i}.png`;
    img.onload = function() {
      gif.addFrame(img);
    }
  }

  // Render the GIF and set it as the source of the <img> tag
  gif.on('finished', function(blob) {
    const imgTag = document.getElementById("myGif");
    imgTag.src = URL.createObjectURL(blob);
  });

  // Render frames into an animated GIF
  gif.render();
}

相关问题