There is such code:

<!DOCTYPE html> <html> <head> <title>Canvas from scratch</title> <meta charset="utf-8"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> function getRandomInt() { return Math.floor(Math.random() * (255 - 0)) + 0; } $(document).ready(function() { var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); for (var i = 0; i < 10; i++) { var coordinates = 70*i; ctx.fillStyle = "rgb("+getRandomInt()+", "+getRandomInt()+", "+getRandomInt()+")"; ctx.fillRect(coordinates, 0, 70, 70); ctx.font = "bold 30px Verdana,sans-serif"; ctx.lineWidth = 1; ctx.strokeText("Н", 25*i, 50); } }); </script> </head> <body> <canvas id="myCanvas" width="700" height="70"> <!-- Insert fallback content here --> </canvas> </body> </html> 

If you run it, then loom the squares of 10 pieces. with different colors 70 on 70 px and letters 10 pieces. but how to make each letter in the middle of its square?

  • 2
    Well, ctx.strokeText("Н", 70*i + 25, 50); where 70 is the width of the square, 25 is the indent on the left - Alexey Shimansky
  • @ Alexey Shimansky, +25 - brrrrrrrrrrrrrr ... - Qwertiy
  • @Qwertiy agree. I was broke to write a calculated value .. for there the text width can still be set .... so taking into account the magic numbers of the vehicle it will work) - Alexey Shimansky
  • one
    @ Alexey Shimansky, see the answer. Canvas is able to center himself. - Qwertiy
  • @Qwertiy ugu .. - Alexey Shimanskyj

1 answer 1

 ctx.textAlign = 'center'; ctx.strokeText("Н", 70*(i+.5), 50); 

 $(function() { function getRandomInt() { return Math.floor(Math.random() * 256); } var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); for (var i = 0; i < 10; i++) { var coordinates = 70*i; ctx.fillStyle = "rgb("+getRandomInt()+", "+getRandomInt()+", "+getRandomInt()+")"; ctx.fillRect(coordinates, 0, 70, 70); ctx.font = "bold 30px Verdana,sans-serif"; ctx.textAlign = 'center'; ctx.lineWidth = 1; ctx.strokeText("Н", 70*(i+.5), 50); } }); 
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <canvas id="myCanvas" width="700" height="70"></canvas>