Open Menu dzosoft
Close Menu dzosoft

   ALL ABOUT COMPUTER SCIENCE AND TECHNOLOGY


                             




NICOTINE FREE

Publish perfectly-optimized content in 1-click









 
 
 

How to draw in the browser with JavaScript

 

HTML5 introduced the canvas object which allows drawing in the browser with JavaScript. Canvas is basically used to display graphics but it is even possible to make 3D games.
In this article, we will see how to draw lines, simple shapes, fill them and find your way around the drawing area.

 

The HTML canvas object

 

The word canvas means canevas. It is therefore very oriented graphic and artistic creation. It is simply declared by the tag canvas and behaves on display like a div.
Let's define a style for all the canvases in our article:

canvas {
  border:2px solid #999;
  background-color:#fff;
}


Let's create our first canvas:

<canvas id="canvas1" width="800" height="300">Your browser is too old</canvas>


The location in the canvas is done by Cartesian coordinates (x, y) with the origin (0, 0) at the top left

 
How to draw in the browser with JavaScript
 

It is also necessary to master the management of angles and trigonometry for drawing circles.

 
How to draw in the browser with JavaScript
 

 

Drawing lines

 

<html>
<head>
<style>
canvas {
  border:2px solid #999;
  background-color:#000;
}
</style>
</head>

<body> <canvas id="canvas1" width="700" height="200">Your browser is too old</canvas> <script> var myCanvas=document.getElementById("canvas1"); var ctx = myCanvas.getContext("2d"); ctx.lineWidth="8"; ctx.strokeStyle="#fff";
ctx.beginPath(); // draw 1 ctx.moveTo(30, 30); ctx.lineTo(40, 10); ctx.lineTo(40, 60); ctx.stroke();
ctx.beginPath(); // draw 2 ctx.moveTo(80, 80); ctx.lineTo(60, 80); ctx.lineTo(60, 60); ctx.lineTo(80, 60); ctx.lineTo(80, 40); ctx.lineTo(60, 40); ctx.stroke(); </script> </body> </html>


  and 2 are displayed at runtime!

 
How to draw in the browser with JavaScript
 

A few simple explanations to understand the main principles of drawing on canvas are essential:
Classically, we look for the canvas with getElementById() which informs the variable myCanvas.
The variable ctx is fed by the call to getContext() object-specific method HTMLCanvasElement.
Then all drawing actions in the canvas go through method calls and property assignments on this context.
The property lineWidth contains the width of the pencil.

The property strokeStyle contains the pencil color.
The method beginPath() initializes a plot.
The method moveTo(x, y) moves the pointer to position (x, y).
The method lineTo(x, y) draws a line from the cursor position to the position (x, y).
The method stroke() displays the unfilled drawing initialized in the canvas. As long as stroke() is not called, the drawing of a path is not displayed.


 

Draw shapes

 
The management of forms is quite extensive
<canvas id="canvas2" width="650" height="300">Your browser is too old</canvas>


Some examples of drawing shapes:

<html>
<head>
<style>
canvas {
  border:2px solid #999;
  background-color:#000;
}
</style>
</head>

<body> <canvas id="canvas2" width="700" height="200">Your browser is too old</canvas> <script> var myCanvas=document.getElementById("canvas2"); var ctx = myCanvas.getContext("2d"); /* A circle and an arc of a circle */ ctx.lineWidth="4"; ctx.strokeStyle="#fff"; ctx.beginPath(); ctx.arc(300, 105, 65, 0, 2*Math.PI); ctx.stroke();
/* A closed path (a triangle) */ ctx.lineWidth="4"; ctx.strokeStyle="#D8FF69"; ctx.beginPath(); ctx.moveTo(60,60); ctx.lineTo(190,35); ctx.lineTo(50,160); ctx.closePath(); ctx.stroke();
ctx.beginPath(); ctx.arc(500, 105, 25, Math.PI/2, 2*Math.PI); ctx.stroke();
/* A rectangle */ ctx.lineWidth="8"; ctx.strokeStyle="#69FFE7"; ctx.rect(20,20,660,160) ctx.stroke();

</script> </body> </html>


Here are the shapes that appear:
 
How to draw in the browser with JavaScript
 

The method rect(x, y, width, height) draws a rectangle whose upper left corner is in (x,y) with width and height as dimensions.

The method closePath() closes an open path with beginPath().

 

Filling modes

 

Here are the 3 forms to fill in

<html>
<head>
<style>
canvas {
  border:1px solid #999;
  background-color:#000;
}
</style>
</head>

<body> <canvas id="canvas3" width="700" height="200">Your browser is too old</canvas> <script> var myCanvas=document.getElementById("canvas3"); var ctx = myCanvas.getContext("2d");
/* A solid color rectangle */ ctx.lineWidth="2"; ctx.fillStyle="#316AC5"; ctx.fillRect(20,20,660,160)
/* Two circles with color gradients */ var myGradient = ctx.createLinearGradient(215, 0, 270, 0); myGradient.addColorStop(0, '#1B606B'); myGradient.addColorStop(1, '#ffffff'); ctx.fillStyle = myGradient; ctx.beginPath(); ctx.arc(250, 105, 55, 2*Math.PI, 0); ctx.fill();

myGradient = ctx.createRadialGradient(450, 80, 50, 450, 85, 2*Math.PI); myGradient.addColorStop(0, '#ffa500'); myGradient.addColorStop(1, '#ffffff'); ctx.fillStyle = myGradient; ctx.beginPath(); ctx.arc(450, 105, 55, 0, 2*Math.PI); ctx.fill();

/* A shape defined by a path filled with an image */ var img = new Image(); img.src = 'pattern.png?1'; img.onload = function() { var pattern = ctx.createPattern(img, 'repeat'); ctx.fillStyle = pattern; ctx.beginPath(); ctx.moveTo(500,60); ctx.lineTo(590,35); ctx.lineTo(600,160); ctx.lineTo(490,90); ctx.fill(); }
/* A dark square with transparency */ ctx.fillStyle = 'rgba(15, 15, 15, 0.3)'; ctx.fillRect(250, 5, 100, 100); </script> </body> </html>




The property fillStyle contains the fill style. This example shows the case of a solid color, a color gradient or a pattern resulting from an image repetition.
The method fillRect draws a rectangle filled with the style defined in fillStyle.

 
How to draw in the browser with JavaScript
 

The method fill() fills a path with the previously defined style. It is to be related to stroke() which traces the contours of the path.
Color gradients are objects CanvasGradient representing precisely defined gradients from a shape and colors. Canvas accepts 2 types of gradients.
The linear gradient created by createLinearGradient(x1, y1, x2, y2) defines a vector between the points (x1, y1) and (x2, y2). This vector is colored by a gradient of colors added by addColorStop(number, colorCode).
The circular gradient created by createRadialGradient(x1, y1, r1, x2, y2, r2) defines 2 circles with their position and radius.
Gradients require a bit of trial and error to get the desired effect...
Finally, there is a possibility to fill a shape with a repeated image, the effect of which is comparable to the CSS property background-url. The subtlety is that you have to wait for the image to load to be able to create the pattern with createPattern(). This forces detected the event onload on the JavaScript objectImage.


 

Write text

 

Of course, the canvas makes it possible to display text simply.

<canvas id="canvas1" width="700" height="200">Your browser is too old</canvas>

Here is an example for writing text:

<html>
<head>
<style>
canvas {
  border:1px solid #999;
  background-color:#fff;
}
</style>
</head>
<body>
<canvas id="canvas3" width="700" height="200">Your browser is too old</canvas>
<script>
var myCanvas=document.getElementById("canvas3");
var ctx = myCanvas.getContext("2d");
ctx.font="50px arial";
ctx.strokeText("How to draw with JavaScript",10,50);
ctx.fillText("How to draw with JavaScript",10,110);
ctx.fillStyle="#79EEFF";
ctx.fillText("How to draw with JavaScript",10,170);
ctx.stroke();
</script>
</body>
</html>


And here are some examples of text styles!

 
How to draw in the browser with JavaScript
 

font contains text style properties.
strokeText() displays letter outlines.
fillText() displays full text.

 

Text position

 

measureText() returns the width in pixels of the text occupied in the canvas. This data allows you to position the text more precisely.

By default, the text position is the lower left corner of the text box.
The property textBaseline contains the text support line type. By default, the value is alphabetic with a text that is based on the main line of writing.

 

Transforms and rotations

 

There is a way to perform transformations before drawing on the canvas with setTransform() And rotate().
Here is an example to rotate a text vertically. You quickly realize that the code needed to perform this relatively simple operation is both long and complex. Creating a function seems really useful.

<html>
<head>
<style>
canvas {
  border:1px solid #999;
  background-color:#fff;
}
</style>
</head>

<body> <canvas id="canvas4" width="700" height="200">Your browser is too old</canvas> <script> var myCanvas=document.getElementById("canvas4"); var ctx = myCanvas.getContext("2d"); ctx.font="30px arial"; /* Text without transformation */ ctx.fillText("How to draw with JavaScript",10,50);
/* Rotate an eighth of a turn */ ctx.rotate(Math.PI/4); ctx.fillText("How to draw with JavaScript",10,50);
/* Display text vertically in position (280, 200) */ ctx.setTransform(1, 0, 0, 1, 280, 220); ctx.rotate(3*Math.PI/2); ctx.fillText("How to draw with JavaScript",0,0); </script> </body> </html>


And here are some examples of text rotation!

 
How to draw in the browser with JavaScript
 
By default the rotation is done on the point (0, 0) of the canvas. It is therefore necessary to use the last 2 parameters of setTransform() to translate the point of rotation.

It might also interest you


How to make Ajax calls with XMLHTTPRequest

How to make Drag and Drop in HTML 5 and JavaScript API

How to copy text to clipboard using html, css and javascript

How to create a responsive slideshow with CSS and JavaScript

How to Capture Photo From Camera using Javascript


Leave comment
          

Save nickname and email in this browser for the next time.



Loading...     
close publicity
Dazzle with your smile!