Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Gộp nhiều ảnh thành một (Canvas Composite) bằng JavaScript


Dùng <canvas> và CanvasRenderingContext2D.drawImage(). globalAlpha điều chỉnh độ trong suốt (0-1). Vẽ ảnh 1 (alpha=1), sau đó vẽ ảnh 2 lên trên (alpha=0.5) tạo hiệu ứng blend.

Ví dụ

Gộp 2 ảnh từ picsum.photos:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Combine images Canvas</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    img { max-width: 250px; border: 1px solid #ccc; margin: 5px; }
    canvas { border: 1px solid #333; margin-top: 10px; }
  </style>
</head>
<body>
  <h1>Gộp nhiều ảnh thành một bằng Canvas</h1>
  <img class="image" src="https://picsum.photos/id/845/250/250.jpg" alt="Ảnh 1"/>
  <img class="image" src="https://picsum.photos/id/925/250/250.jpg" alt="Ảnh 2"/>
  <br>
  <canvas class="result" width="250" height="250"></canvas>
  <br>
  <button class="Btn">GỘP 2 ẢNH</button>
  <h3>Nhấn nút để vẽ ảnh 1 rồi blend ảnh 2 lên trên (alpha 0.5)</h3>
  <script>
    const img1 = document.querySelectorAll('.image')[0];
    const img2 = document.querySelectorAll('.image')[1];
    const canvas = document.querySelector('.result');
    const ctx = canvas.getContext('2d');
    const btn = document.querySelector('.Btn');
    // Đợi ảnh load xong mới vẽ
    const waitLoad = (img) => img.complete ? Promise.resolve() : new Promise(r => img.onload = r);
    btn.addEventListener('click', async () => {
      await Promise.all([waitLoad(img1), waitLoad(img2)]);
      canvas.width = img1.naturalWidth;
      canvas.height = img1.naturalHeight;
      ctx.globalAlpha = 1.0;
      ctx.drawImage(img1, 0, 0);
      ctx.globalAlpha = 0.5;
      ctx.drawImage(img2, 0, 0);
    });
  </script>
</body>
</html>

Kết quả

Canvas hiển thị ảnh 1 bên dưới, ảnh 2 mờ 50% lên trên.

Lưu ý: CORS: ảnh phải cùng origin hoặc server cho phép Access-Control-Allow-Origin và img.crossOrigin = 'anonymous'. Code gốc thiếu xử lý load ảnh -> đã thêm await.