用画布创建图案

问题描述

我想用画布创建一个样式。应该使用的图片也应该先被整理。我已经使用以下代码执行过类似this的操作:

    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,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,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>

现在,我想用它创建某种网格,它看起来应该像this

我该怎么做?

解决方法

最好的方法是使用两个for循环遍历x和y值!您可以使用这些循环将绘制文本的部分包围起来,并使用不断变化的x和y值代替硬编码的值。

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,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,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
        }
    }
}

使用ctx.translate(x,y)而不是ctx.fillText('Text',x - 70,y + 300)的原因是因为使用fillText会以一定角度移动网格,而不仅仅是旋转字母。