0

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?

davykiash
  • 1,796
  • 5
  • 27
  • 60
  • 3
    Work out what 80% of the width of the canvas is... generate a random value based on that... then add on 10% of the width of the canvas to that value – freefaller May 06 '21 at 14:03

1 Answers1

1

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>
freefaller
  • 19,368
  • 7
  • 57
  • 87
  • Thanks also for the pointer on the behaviour of the fonts. – davykiash May 06 '21 at 14:42
  • 1
    You're welcome - it's not an exact science, especially when you're dealing with fonts. You're maybe better investigating the use of [.arc](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/arc) instead. Good luck with the rest of your project – freefaller May 06 '21 at 14:45
  • Ah, of course, that's only if you want circles... I've just re-read your title/question and you do state letters... so ignore that .arc comment! – freefaller May 06 '21 at 14:45