首页 > 解决方案 > 用画布创建图案

问题描述

我想用画布创建一个pettern。应该使用的图片也应该首先生成。我已经用这段代码做了这样的事情:

    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>

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

我怎样才能做到这一点?

标签: htmlcanvas

解决方案


最好的方法是使用两个 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, 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
        }
    }
}

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


推荐阅读