Mr Brickstar
Mr Brickstar

Reputation: 308

Create pattern with canvas

I would like to create a pettern with canvas. The Picture which should be used should also be gernerated first. I already did something like this with this code:

    document.addEventListener('DOMContentLoaded', function () {


 async function draw() {
  var canvas = document.getElementById('canvas1')
  var ctx = canvas.getContext("2d");
  var canvas = ctx.createImageData(500, 300);
  ctx.fillStyle = "#7289DA";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

    // Select the color of the stroke
    ctx.strokeStyle = '#74037b';
    // Draw a rectangle with the dimensions of the entire canvas
  ctx.strokeRect(0, 0, canvas.width, canvas.height);
  
  ctx.font = 'bold 70px sans-serif';
  // Select the style that will be used to fill the text in
  ctx.save();
  ctx.rotate(1.7*Math.PI);
  ctx.fillStyle = '#23272A';
  ctx.fillText('Text', -70, 300);
  ctx.restore();
    // Actually fill the text with a solid color

}
    
draw();

}); 
 <canvas id="canvas" width="1500" height="900">Beispiel für eine Kachelung eines Musters in Canvas.</canvas>

Now I want to create some kind of grid with it, it should look like this

How can I do that?

Upvotes: 0

Views: 249

Answers (1)

VeryGoodDog
VeryGoodDog

Reputation: 335

The best way would be using two for loops to go over the x and y values! You can surround the part that draws text with these loops and use the changing x and y values instead of hard-coded ones.

async function draw() {
    var canvas = document.getElementById('canvas1')
    var ctx = canvas.getContext("2d");
    var canvas = ctx.createImageData(500, 300);
    ctx.fillStyle = "#7289DA";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // Select the color of the stroke
    ctx.strokeStyle = '#74037b';
    // Draw a rectangle with the dimensions of the entire canvas
    ctx.strokeRect(0, 0, canvas.width, canvas.height);
  
    ctx.font = 'bold 70px sans-serif';
    ctx.fillStyle = '#23272A';
    // Select the style that will be used to fill the text in
    for (var x = 0; x < canvas.width; x += 100 ) { // 100 is the width
        for (var y = 0; y < canvas.height; y += 70) { // 70 is the height
            ctx.save();
            ctx.translate(x, y); // offset the text
            ctx.rotate(1.7*Math.PI);
            ctx.fillText('Text', -70, 300);
            ctx.restore();
            // Actually fill the text with a solid color
        }
    }
}

The reason ctx.translate(x, y) is used instead of ctx.fillText('Text', x - 70, y + 300) is because using fillText would move the grid at an angle instead of just rotating the letters.

Upvotes: 1

Related Questions