HTML5 Canvas - repeat the text of the entire canvas size

Is there a way to draw all sizes inside canyons? I checked that I can repeat the image, but just want to repeat the text.

As a plus, if the text could move along each line, it could be great. An example of the effect that I need if I set "1234567" as the text:

1234567 1234567 1234567 1234567 1234567 1234567
234567 1234567 1234567 1234567 1234567 1234567 
34567 1234567 1234567 1234567 1234567 1234567 1
4567 1234567 1234567 1234567 1234567 1234567 12
567 1234567 1234567 1234567 1234567 1234567 123
67 1234567 1234567 1234567 1234567 1234567 1234
7 1234567 1234567 1234567 1234567 1234567 12345
 1234567 1234567 1234567 1234567 1234567 123456
1234567 1234567 1234567 1234567 1234567 1234567
+4
source share
2 answers

measureText (TXT)

You can measure text using canvas. canvas.measureText(txt).width

Here is a basic example with various limitations. To create large canvases, one more math is required ...

txtHeight- this is basically a line-height. offsetis the distance you want to move the text.

- , .

var b=document.createElement('canvas');
b.width=320;
b.height=160;
c=b.getContext("2d");
function draw(txt){
 c.font="20px Arial";
 var txtHeight=25;
 var offset=5;
 var w=Math.ceil(c.measureText(txt).width);
 var txt=new Array(w*2).join(txt+' ');//change the multipler for more lines
 for(var i=0;i<Math.ceil(b.height/txtHeight);i++){
  c.fillText(txt,-(i*offset),i*txtHeight);
 }
}
document.body.appendChild(b);
draw('1234567');

Demo

https://jsfiddle.net/wav0xmLz/1/

.

, , txt.... . iiii TTTT .

.... , , ... .

split,shift,join,push

https://jsfiddle.net/kds7zkkf/

+2

. .

CanvasRenderingContext2D.prototype.wrapText = function (text, x, y, maxWidth, lineHeight) {

  var lines = text.split("\n");

  for (var i = 0; i < lines.length; i++) {

    var words = lines[i].split(' ');
    var line = '';

    for (var n = 0; n < words.length; n++) {
      var testLine = line + words[n] + ' ';
      var metrics = this.measureText(testLine);
      var testWidth = metrics.width;
      if (testWidth > maxWidth && n > 0) {
        this.fillText(line, x, y);
        line = words[n] + ' ';
        y += lineHeight;
      } else {
        line = testLine;
      }
    }

    this.fillText(line, x, y);
    y += lineHeight;
  }
};



var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");

ctx.font = "12px sans-serif";
ctx.textBaseline = "top";
var str = '';
for (var i = 0; i < 100; i++) {
  str += '1234567 ';
}
ctx.wrapText(str,0,0,myCanvas.width,16);
canvas {
  border:1px solid red;  
}
<canvas id="myCanvas" width="400" height="200"></canvas>
Hide result

: HTML5 canvas ctx.fillText ?

+2

Source: https://habr.com/ru/post/1625723/


All Articles