Newer
Older
minerva / Base / res / html / misc / canvas-clip-path.html
@minerva minerva on 13 Jul 1 KB Initial commit
<style>
  canvas {
    border: 1px solid black;
  }
</style>
<!-- Examples taken from MDN -->
<b>(nonzero) path clipping:</b><br>
<canvas id="canvas1" width="200" height="160"></canvas>
<br>
<b>evenodd path clipping:</b><br>
<canvas id="canvas2" width="200" height="160"></canvas>
<script>
{
  const canvas = document.getElementById("canvas1");
  const ctx = canvas.getContext("2d");

  // Create circular clipping region
  ctx.beginPath();
  ctx.arc(0/*FIMXE: Should be 100, but ctx.arc() is currently broken*/, 75, 50, 0, Math.PI * 2);
  ctx.clip();

  // Draw stuff that gets clipped
  ctx.fillStyle = "blue";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "orange";
  ctx.fillRect(0, 0, 100, 100);
}
</script>
<script>
{
  const canvas = document.getElementById("canvas2");
  const ctx = canvas.getContext("2d");

  // Create clipping path
  let region = new Path2D();
  region.rect(80, 10, 20, 130);
  region.rect(40, 50, 100, 50);
  ctx.clip(region, "evenodd");

  // Draw stuff that gets clipped
  ctx.fillStyle = "blue";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}
</script>