简体   繁体   中英

How to draw a grid over an Unusual shape on canvas

I am trying to work out a way to draw a grid over a png image so that the grid only is drawn on parts of the image.

I do not want the grid on any parts of the page that is not the shape.

How do you do this?

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(75, 50);
ctx.lineTo(40, 205);
ctx.lineTo(300, 25);
ctx.fillStyle = 'green';
ctx.fill();


function drawGrid(context) {
  context.globalCompositeOperation = 'destination-out   ';

  for (var x = 40.5; x < 300; x += 10) {
    context.moveTo(x, 0);
    context.lineTo(x, 300);
  }

  for (var y = 0.5; y < 301; y += 10) {
    context.moveTo(0, y);
    context.lineTo(300, y);
  }

  context.strokeStyle = "#ddd";
  context.stroke();
}

drawGrid(ctx)

https://jsfiddle.net/m8679fk4/2/

First, change your composite operation to destination-out and furthermore put the call to drawGrid(context); into the onload handler, right after context.drawImage(img, 0, 0); - otherwise the grid might get drawn before the image even finished loading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM