如何將 Canvas 圖形轉換為影像?


HTML canvas 圖形提供了許多建立多功能物件的選項。在使用 Canvas 時,您可能希望將圖形轉換為真實的影像,以便下載或列印。本文將幫助您建立圖形並將其儲存到您的裝置上。

示例

在這裡,我們使用 javascript Canvas 建立圖形,然後將圖形轉換為影像。在此示例中,我們將建立一個實心紅色正方形,然後使用按鈕將其下載到裝置。

演算法

步驟 1:在畫布上建立圖形。

步驟 2:建立圖形後,獲取圖形元素的 ID。

步驟 3:建立一個影像物件,並使用 toDataURL() 函式將影像的源 (src) 設定為畫布的資料 URL。

步驟 4:現在將影像源分配給連結的 href 屬性。

步驟 5:為畫布影像建立一個唯一的檔名,因為您的影像將使用此名稱儲存。

步驟 6:插入一個按鈕元素以儲存此影像。

示例

<!DOCTYPE html>
<html>
<head>
  <title>Canvas to Image Conversion</title>
</head>
<body>
  <canvas id="myCanvas" width="200" height="200"></canvas>
  <button onclick="convertToImage()">Convert to Image</button>

  <script>
    function convertToImage() {
      // Get the canvas element
      const canvas = document.getElementById('myCanvas');
      const context = canvas.getContext('2d');

      // Clear the canvas
      context.clearRect(0, 0, canvas.width, canvas.height);

      // Draw a red square on the canvas
      context.fillStyle = 'red';
      context.fillRect(50,50,100,100);
     

      // Create an image element
      const image = new Image();

      // Assign the canvas content as the source of the image
      image.src = canvas.toDataURL();

      // Create a temporary link element to download the image
      const link = document.createElement('a');
      link.href = image.src;
      link.download = 'canvas_image.png';

      // Trigger the link programmatically to start the download
      link.click();
    }
  </script>
</body>
</html>

示例

在此示例中,我們將嘗試將複雜的畫布圖形轉換為影像。

演算法

步驟 1:在畫布上建立圖形。

步驟 2:獲取圖形元素的 ID 並建立一個影像物件。

步驟 3:使用 toDataURL() 函式設定影像的源。

步驟 4:建立畫布圖形。

步驟 5:指定影像檔名。

步驟 6:透過設定影像顏色和尺寸來建立圖形。

步驟 7:設定影像轉換按鈕。

示例

<!DOCTYPE html>
<html>
<head>
  <title>Canvas to Image Conversion</title>
</head>
<body>
  <canvas id="myCanvas" width="200" height="200"></canvas>
  <button onclick="convertToImage()">Convert to Image</button>

  <script>
    function convertToImage() {
      // Get the canvas element
      const canvas = document.getElementById('myCanvas');
      const context = canvas.getContext('2d');

      // Clear the canvas
      context.clearRect(0, 0, canvas.width, canvas.height);

      // Draw a red square on the canvas
      context.fillStyle = 'red';
      context.fillRect(50,50,100,100);
     

      // Create an image element
      const image = new Image();

      // Assign the canvas content as the source of the image
      image.src = canvas.toDataURL();

      // Create a temporary link element to download the image
      const link = document.createElement('a');
      link.href = image.src;
      link.download = 'canvas_image.png';

      // Trigger the link programmatically to start the download
      link.click();
    }
  </script>
</body>
</html>

結論

透過遵循幾行程式碼和觸發事件,可以輕鬆地將畫布圖形轉換為影像。在本文中,我們介紹了兩種在畫布上建立圖形並將其另存為單獨影像檔案的方法。

更新於: 2023年8月9日

5K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告