1

I'm trying to fill a rectangle with diagonal lines at 30 degrees that don't get clipped by the canvas. Each line should start and end on the edges of the canvas, but do not go outside the canvas.

I've gotten somewhat of a result but is struggling to understand how I can fix the ends so the lines become evenly distributed:

enter image description here

Here is the code I got so far:

const myCanvas = document.getElementById("myCanvas");
const _ctx = myCanvas.getContext("2d");
const canvasWidth = 600;
const canvasHeight = 300;

// Helper function
const degToRad = (deg) => deg * (Math.PI / 180);

const angleInDeg = 30;
const spaceBetweenLines = 16;
const lineThickness = 16;


_ctx.fillStyle = `black`;
_ctx.fillRect(0, 0, canvasWidth, canvasHeight);


const step = (spaceBetweenLines + lineThickness) / Math.cos(angleInDeg * (Math.PI / 180));

for (let distance = -canvasHeight + step; distance < canvasWidth; distance += step) {
  let x = 0;
  let y = 0;
  
  if(distance < 0) {
    // Handle height
    y = canvasHeight - (distance + canvasHeight);
  } else {
    // Handle height
    x = distance;
  }

  const lineLength = canvasHeight - y;
  const slant = lineLength / Math.tan(degToRad((180 - 90 - angleInDeg)));
 
  const x2 = Math.min(x + slant, canvasWidth);
  const y2 = y + lineLength;

  _ctx.beginPath();
  _ctx.moveTo(x, y);
  _ctx.lineTo(x2, y2);

  _ctx.lineWidth = lineThickness;
  _ctx.strokeStyle = 'green';
  _ctx.stroke();
}

and a JSFiddle for the code.

What I'm trying to achieve is drawing a pattern where I can control the angle of the lines, and that the lines are not clipped by the canvas. Reference photo (the line-ends don't have flat):

enter image description here

Any help?

My example is in Javascript, but it's more the logic I'm trying to wrap my head around. So I'm open to suggestions/examples in other languages.

Update 1 If the angle of the lines is 45 degree, you will see the gutter becomes correct on the left side. So I'm suspecting there is something I need to do differently on my step calculations.

My current code is based on this answer.

lassemt
  • 164
  • 1
  • 11

1 Answers1

0

Maybe try something like this for drawing the lines

for(var i = 0; i < 20; i++){
   _ctx.fillrect(i * spaceBetweenLines + lineThickness, -100, canvas.height + 100, lineThickness)
}
  • Thank you for answering, Jake. This will unfortunatly have the canvas clip the line. I'm looking for something that draw the lines so they fit inside the canvas as I'm going to add rounded edges ends. later on. – lassemt Nov 06 '20 at 14:01
  • Ok I don't really know how to do that. Sorry that I could not give you a good answer. – Jake Grubba Nov 07 '20 at 15:06