Drawing random dots with Canvas

- Andrés Cruz

En español
Drawing random dots with Canvas

In this article we will practice a little more with the use of Canvas in HTML5, basically we will draw a bunch of spheres whose positions are random. If you don't know how to get started with Canvas in HTML5, you can read the previous article in which we take the first steps with this API: Basic use of the canvas.

This exercise is still very simple to perform; I will ignore several explanations on how to draw with this API because this was already the topic of a previous blog article: Basic use of the canvas.

  • The first thing we must do is obtain a reference to the canvas with which we want to work: var myCanvas = document.getElementById("myCanvas");
  • Once the canvas has been referenced, we obtain its dimensions and calculate how far we can draw:
var width = myCanvas.width; var height = myCanvas.height; var maxWidth = width-radius; var maxHeight = height-radius;

Finally, we draw:

var ctx=myCanvas.getContext("2d");
for(i=0; i<n; i++){ 

var centerX = Math.floor(Math.random() * maxWidth);
var centerY = Math.floor(Math.random() * maxHeight);

ctx.fillStyle = "red"; // color de las estrellas
  • We use the fillStyle attribute to select a fill color and the fill() function to indicate that the figure will be filled.
  • Lines 5 and 6 calculate the random positions within the Canvas dimensions where the spheres will be drawn.

Complete example 1

You can try the complete example by clicking here.

Using the previous example as a base, we will create a new example which will allow us to modify the number of spheres, the radius and color of the spheres through some inputs which we reference and take their values in the JavaScript:

var radius = document.getElementById("radio").value; 
var n = document.getElementById("n").value; 
var color = document.getElementById("color").value;

In addition to the above; the next line myCanvas.width = width; allows you to clean the canvas (the previous drawing).

Complete example 2

You can try the complete example by clicking here.

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.