Search code examples
javascriptcanvashtml5-canvas

Placing a letter randomly in a canvas offset by a % from border


I have this canvas where I place a letter randomly within the canvas.

var w = Math.random() * canvas.width;
var h = Math.random() * canvas.height;

drawRandomCircle(canvas,w,h);

function drawRandomCircle(canvas,w,h) 
{
    
    var fontSize = '35';            
    var ctx = canvas.getContext("2d");
    
    var color = 'rgba(245, 66, 66,1.0)';
    ctx.fillStyle = color;
    ctx.font = fontSize + 'pt Arial';
    ctx.fillText('O', w, h);
    
} 

The results:

Result 1

I would like to improve further on the function to include an offset in % from the canvas boundary to limit where the letter will appear.

The results would be similar to something similar to this.

Results 2

Any ideas?


Solution

  • You need to take into account the 10% on the borders.

    Try the following which uses this principle... but also remember that the co-ordinates for the canvas are top-left based... but when you do the font it will go UP (not down) so you have to take that into account as well.

    var canvas = document.getElementsByTagName("canvas")[0];
    var fontSizePx = 35;
    
    // Get 10% of the width/height
    var cw = (canvas.width / 10);
    var ch = (canvas.height / 10);
    
    // Get 80% of the width/height but minus the size of the font
    var cw80 = (cw * 8) - fontSizePx;
    var ch80 = (ch * 8) - fontSizePx;
    
    for(var i = 0; i < 10; i++) {
      // Get random value within center 80%
      var w = (Math.random() * cw80) + cw;
      // Add on the size of the font to move it down
      var h = (Math.random() * ch80) + ch + fontSizePx;
      drawRandomCircle(canvas,w,h);
    }
    
    function drawRandomCircle(canvas,w,h) {
      var ctx = canvas.getContext("2d");
      var color = 'rgba(245, 66, 66,1.0)';
      ctx.fillStyle = color;
      ctx.font = fontSizePx.toString() + 'px Arial';
      ctx.fillText('O', w, h);
    }
    canvas {
      border:1px solid black;
    }
    <canvas></canvas>