Draw points (circles) on a canvas with javascript html5

Draw points (circles) on a canvas with javascript html5

The <canvas> tag is used to draw graphics, on the fly, via Javascript. The  tag is only a container for graphics, you must use a script to actually draw the graphics. In this article you'll learn how to draw in the canvas a point according to the clicked point by the user.

To start create a canvas tag in your document with the size that you want.

<!-- The canvas tag -->
<canvas id="canvas" width="690" height="651"></canvas>

To draw points on a canvas when the user clicks on it, we need to retrieve the click event and get the coordinates of that click.To get the mouse coordinates relative to an HTML5 Canvas, we can create a getPosition() method which returns the mouse coordinates (x,y) based on the position of the client mouse and the position of the canvas obtained from the getBoundingClientRect() method of the window object.

// Event will be a click event which can be retrieved as first parameter in the addEventListener(function(event){}); or in jQuery with $("selector").click(function(event){});
function getPosition(event){
     var rect = canvas.getBoundingClientRect();
     var x = event.clientX - rect.left; // x == the location of the click in the document - the location (relative to the left) of the canvas in the document
     var y = event.clientY - rect.top; // y == the location of the click in the document - the location (relative to the top) of the canvas in the document
     
     // This method will handle the coordinates and will draw them in the canvas.
     drawCoordinates(x,y);
}

Now, our drawCoordinates method will draw the point according to the location of the click in the canvas. This receives as first parameter the x (horizontal) coordinate of the canvas and as second parameter the y (vertical) coordinate relative to the canvas.

function drawCoordinates(x,y){
    var pointSize = 3; // Change according to the size of the point.
    var ctx = document.getElementById("canvas").getContext("2d");


    ctx.fillStyle = "#ff2626"; // Red color

    ctx.beginPath(); //Start path
    ctx.arc(x, y, pointSize, 0, Math.PI * 2, true); // Draw a point using the arc function of the canvas with a point structure.
    ctx.fill(); // Close the path and fill.
}

The following fidle shows an already working example of all the above methods. Go to the Result tab and see how it works, draw many points on the hen !

This code is friendly with all the resolutions as it's kept the most simple as possible. Even if you zoom on the document, the coordinates will be drawn correctly. Have fun !

Become a more social person