<div>
  <h3>mask base clip</h3>
  <canvas id="clip-cvs"></canvas>  
</div>

<div>
  <h3>mask base globalCompositeOperation</h3>
  <canvas id="gco-cvs"></canvas>
</div>
  async function clipMask({ img, WIDTH, HEIGHT, windowRect }) {
    const cvs = document.getElementById("clip-cvs");
    const ctx = cvs.getContext("2d");
    const { x, y, width, height } = windowRect;
    cvs.width = WIDTH;
    cvs.height = HEIGHT;
    ctx.drawImage(img, 0, 0, WIDTH, HEIGHT);
    ctx.save();
    ctx.fillStyle = "rgba(0,0,0,0.6)";
    ctx.fillRect(0, 0, WIDTH, HEIGHT);
    ctx.rect(x, y, width, height);
    ctx.clip();
    ctx.drawImage(img, 0, 0, WIDTH, HEIGHT);
    ctx.restore();
  }

  async function gCOMask({ img, WIDTH, HEIGHT, windowRect }) {
    const cvs = document.getElementById("gco-cvs");
    const ctx = cvs.getContext("2d");
    const { x, y, width, height } = windowRect;
    cvs.width = WIDTH;
    cvs.height = HEIGHT;
    ctx.save();
    ctx.fillStyle = "rgba(0, 0, 0, 0.6)";
    ctx.fillRect(0, 0, WIDTH, HEIGHT);//绘制全屏半透明蒙层
    ctx.globalCompositeOperation = "destination-out";
    ctx.fillStyle = "#000"; // 随便什么颜色都行
    ctx.fillRect(x, y, width, height);// 这次绘制的区域将会变透明
    ctx.restore();
    ctx.globalCompositeOperation = "destination-over";
    ctx.drawImage(img, 0, 0, WIDTH, HEIGHT);
  }

  !async function() {
    const imgUrl = "https://files.1card1.cn/mps/0/20191111/2bd92a35ff644b478c6becdf753fc43a.jpg";
    const windowRect = {
      x: 200, y: 150,
      width: 400,
      height: 200
    };
    const img = await loadImage(imgUrl);
    if (!img) return;

    const WIDTH = img.width / 2;
    const HEIGHT = img.height / 2;

    const options = {
      img, WIDTH, HEIGHT, windowRect
    };

    clipMask(options);
    gCOMask(options);
  }();

 function loadImage(src) {
    return new Promise(resolve => {
      const img = new Image();
      img.src = src;
      img.addEventListener("load", () => resolve(img));
      img.addEventListener("error", () => resolve(null));
    });
  }

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.