marcus petty
marcus petty

Reputation: 69

Creating a grid which only exists within a shape

am having trouble doing something in Canvas - I want to create a grid that only exists within that shape. I am able to create the gird to fit the shape if it is a square but if the shape is an unusual shape I do not know how to create the grid.

Here is what I have so far: I only want the grid to exist within the shape

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(75, 50);
ctx.lineTo(40, 65);
ctx.lineTo(100, 105);

ctx.lineTo(200, 15);
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 < 501; y += 10) {
    context.moveTo(0, y);
    context.lineTo(300, y);
  }

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

drawGrid(ctx)

https://jsfiddle.net/fom9gtb6/

Upvotes: 0

Views: 47

Answers (2)

Thomas Altmann
Thomas Altmann

Reputation: 1744

You can use context.globalCompositeOperation = 'source-atop';

From MDN

The new shape is only drawn where it overlaps the existing canvas content.

This way the strokeStyle is actually used for the grid instead of erasing parts of the shape, which destination-out will do.

Upvotes: 1

P&#228;rt Johanson
P&#228;rt Johanson

Reputation: 1650

context.globalCompositeOperation = 'destination-out   ';

should be

context.globalCompositeOperation = 'destination-out';

Upvotes: 1

Related Questions