在 JavaScript 生成的图像文件中创建渐变背景

问题描述 投票:0回答:1

我编写了以下代码来创建一个PNG图像文件,该文件将HTML正文的渐变背景打印为图像背景:

const downloadButton = document.getElementById('downloadButton');

    downloadButton.addEventListener('click', function() {
      // Create a canvas element and set its dimensions
      const canvas = document.createElement('canvas');
      canvas.width = 500;
      canvas.height = 300;

      // Get the canvas context
      const ctx = canvas.getContext('2d');

      // Fill the canvas with the background Image
      const bodyStyle = document.body.style;
      const backgroundImage = bodyStyle.backgroundImage || 'white'; // Default to white if not set
      ctx.fillStyle = backgroundImage;
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      // Add text indicating background Image
      ctx.font = '20px Arial';
      ctx.fillStyle = 'black';
      const rgbColor = getRGBColor(backgroundImage); // Convert to RGB format
      ctx.fillText(`background Image : ${rgbColor}`, 200, 250); // Adjust position as needed

      // Convert the canvas to a data URL (PNG format)
      const dataURL = canvas.toDataURL('image/png');

      // Convert the data URL to a Blob object
      const blob = new Blob([dataURL.split(',')[1]], { type: 'image/png' });

      // Create a temporary URL for the Blob object
      const fileURL = URL.createObjectURL(blob);

      // Trigger the download of the JPG file
      const link = document.createElement('a');
      link.href = fileURL;
      link.download = 'image.png';
      link.click();

      // Revoke the temporary URL when done (optional)
      URL.revokeObjectURL(fileURL);
    });

    // Function to convert hex color to RGB format
    function getRGBColor(hexColor) {
      if (hexColor.length === 3) {
        hexColor = hexColor.repeat(2); // Duplicate for full RGB
      }
      const r = parseInt(hexColor.slice(0, 2), 16);
      const g = parseInt(hexColor.slice(2, 4), 16);
      const b = parseInt(hexColor.slice(4, 6), 16);
      return `rgb(${r}, ${g}, ${b})`;
    }

它创建了一个名为 image.png 的文件,但无法使用任何工具打开!?

我的目标只是创建一个.png文件,可以渲染HTML正文的背景,即:

body {
   background-image : linear-gradient(0deg ,rgb(0,0,153), rgb(107,0,0));
}

编辑: 我的主要目标不是显示 HTML 正文的背景!

我编写了一段代码,可以生成渐变代码并将其显示在屏幕上,如下所示:(我的代码的一部分)

if (selectedRadio.value === 'option8') {
gradientString = "-webkit-linear-gradient(" + rot + "deg, rgb(" + red1 + "," + green1 + "," + blue1 + "), rgb(" + red2 + "," + green2 + "," + blue2 + "), rgb(" + red3 + "," + green3 + "," + blue3 + "), rgb(" + red4 + "," + green4 + "," + blue4 + ") , rgb(" + red5 + "," + green5 + "," + blue5 + "), rgb(" + red6 + "," + green6 + "," + blue6 + "), rgb(" + red7 + " ," + green7 + "," + blue7 + "), rgb(" + red8 + "," + green8 + "," + blue8 + "))";
}

document.getElementById('result').style.backgroundSize = 'cover';
document.getElementById('result').style.backgroundImage = gradientString;

现在我想在图像文件中创建相同的输出。


编辑2:

我更改了以下代码以实现我的目标,但不再为我创建文件?

        const downloadButton = document.getElementById('downloadButton');

        downloadButton.addEventListener('click', function() {
          // Create a canvas element and set its dimensions
          const canvas = document.createElement('canvas');
          canvas.width = 500;
          canvas.height = 300;
        
          // Get the canvas context
          const ctx = canvas.getContext('2d');
        
          // Create a gradient object using gradientString
          const gradient = new LinearGradient(0, 0, canvas.width, canvas.height); // Adjust coordinates for desired direction
          const gradientParts = gradientString.split(',');
          for (let i = 1; i < gradientParts.length; i++) {
            const colorStop = gradientParts[i].trim().split(')')[0].split(' ');
            const color = colorStop[1];
            const position = parseFloat(colorStop[0].slice(0, -1));
            gradient.addColorStop(position, color);
          }
        
          // Set the fill style of the canvas context to the gradient
          ctx.fillStyle = gradient;
        
          // Fill the canvas with the gradient
          ctx.fillRect(0, 0, canvas.width, canvas.height);
        
          // Add text indicating gradientString content (optional)
          ctx.font = '16px Arial';
          ctx.fillStyle = 'black';
          ctx.fillText(`Gradient String: ${gradientString.slice(0, 50) + "..."}`, 10, 20); // Adjust position and truncate string as needed
        
          // Convert the canvas to a data URL (PNG format)
          const dataURL = canvas.toDataURL('image/png');

  // Convert the data URL to a Blob object
  const blob = new Blob([dataURL.split(',')[1]], { type: 'image/png' });

  // Create a temporary URL for the Blob object
  const fileURL = URL.createObjectURL(blob);

  // Trigger the download of the JPG file
  const link = document.createElement('a');
  link.href = fileURL;
  link.download = 'image.png';
  link.click();

  // Revoke the temporary URL when done (optional)
  URL.revokeObjectURL(fileURL);
        });
javascript jquery
1个回答
0
投票
  1. 您可以只使用画布toBlob
  2. getRGBColor 定义为输入十六进制字符串,如“FF00FF”或“F0F”,因此您不能将“白色”作为背景图像中的默认值。
  3. canvas 上下文 fillStyle 可以支持 'rgb(0, 0, 0)'

样品

downloadButton.addEventListener('click', function() {
  // Create a canvas element and set its dimensions
  const canvas = document.createElement('canvas');
  canvas.width = 500;
  canvas.height = 300;

  // Get the canvas context
  const ctx = canvas.getContext('2d');

  // Fill the canvas with the background Image
  const bodyStyle = document.body.style;
  const backgroundImage = bodyStyle.backgroundImage || 'FFFFFF'; // Default to white if not set
  const rgbColor = getRGBColor(backgroundImage); // Convert to RGB format
  ctx.fillStyle = rgbColor;
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // Add text indicating background Image
  ctx.font = '20px Arial';
  ctx.fillStyle = 'black';
  
  ctx.fillText(`background Image : ${rgbColor}`, 200, 250); // Adjust position as needed

  // Convert the canvas to Blob object
  canvas.toBlob((blob) => {
      // Create a temporary URL for the Blob object
      const fileURL = URL.createObjectURL(blob);

      // Trigger the download of the JPG file
      const link = document.createElement('a');
      link.href = fileURL;
      link.download = 'image.png';
      link.click();

      // Revoke the temporary URL when done (optional)
      URL.revokeObjectURL(fileURL);
  }, 'image/jpeg');      
});
© www.soinside.com 2019 - 2024. All rights reserved.