Home > Article > Web Front-end > How to draw graphics on canvas using js
On the canvas, first use JavaScript's HTML DOM method to find the
The canvas created by the HTML5
Create canvas
Before introducing how to draw graphics, we must first create a canvas using the
<canvas id="myCanvas" width="300" height="200" style="border:2px solid red;"> 当前的浏览器不支持HTML5 canvas标记。 </canvas>
Set the size of the canvas to: width 400px, height 200px, add a 2px red, solid border; give the created canvas an id="myCanvas" value to facilitate finding the canvas element when drawing graphics below.
Rendering:
Use JavaScript to draw graphics on the canvas
Below Let’s introduce how to draw graphics on the canvas:
1. Find the canvas element
When we draw graphics, we first need to find the canvas where we need to draw the graphics. , that is, the
In fact, it is very simple. It can be done by using the HTML DOM method getElementById(). For example:
var canvas = document.getElementById("myCanvas");// 找到画布元素
When we created the canvas before, we added the value of id="myCanvas" to the canvas. Now you can use this ID value to find the
2. Configure the drawing environment and create the drawing object
The getContext() method can return an environment for drawing on the canvas. The only legal value currently is "2d" specifies a two-dimensional drawing environment; this may be expanded to support 3D drawing in the future. Example:
var ctx = canvas.getContext("2d");
Using the ctx object, you can draw graphics in the HTML5 canvas.
3. Draw graphics on the canvas
At this point, you can use the properties and methods of the HTML DOM Canvas object supported by JavaScript to draw graphics. Let's take a look at how to draw graphics through some simple examples:
Example 1: Draw a simple straight line on the canvas
<script> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.beginPath(); // 意思是开始绘制 ctx.moveTo(0,0); ctx.lineTo(300,200); ctx.stroke(); </script>
It can be seen that using it well Several canvas object methods, let’s introduce them below:
beginPath() method: Define the starting path, or reset the current path; indicates the beginning of drawing.
moveTo(x,y) method: used to define the starting point of the straight line.
lineTo(x,y) method: used to define the end position of the straight line.
stroke() method: actually draws the defined path.
Rendering:
Example 2: Draw a simple circle on the canvas
<script> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.arc(95,50,40,0,2*Math.PI); ctx.stroke(); </script>
used The arc() method can create arcs or curves and can be used to draw circles or partial circles.
Rendering:
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
The above is the detailed content of How to draw graphics on canvas using js. For more information, please follow other related articles on the PHP Chinese website!