A quick primer on the usage of HTML5 canvas graphic tags

A quick primer on the usage of HTML5 canvas graphic tags

Canvas is a canvas, a rectangular area, used to draw 2D graphics and images on a web page. Canvas has a variety of methods for drawing paths, rectangles, circles, characters, and adding images.

canvas coordinate system

The coordinate system on the computer is slightly different from the mathematical coordinate system. The origin of the coordinates is in the upper left corner of the drawing area (Canvas in this case), the X axis is facing right, and the Y axis is facing down, as shown in the following figure:

The starting point is the upper left corner, and the coordinates are (0,0). The positions of all elements are positioned relative to the origin. So the coordinates of the upper left corner of the blue square in the figure are x pixels from the left (X axis) and y pixels from the top (Y axis), and the coordinates are (x,y).

 

First, outline the steps of drawing using HTML5 canvas

<canvas></canvas> is a new tag in HTML5, used to draw graphics, in fact, this tag is the same as other tags, its special feature is that the tag can obtain a CanvasRenderingContext2D object, we can use JavaScript script to Control the object for drawing.

<canvas></canvas> is just a container for drawing graphics, in addition to id, class, style and other attributes, there are also height and width attributes. Such as:

<canvas id="MyCanvas" width="300" height="300">

There are three main steps to use javascript to draw on the <canvas>> element:

Get the DOM object corresponding to the <canvas> element, which is a Canvas object; such as:

var canvas = document.getElementById("MyCanvas ");

Call the getContext() method of the Canvas object to get a CanvasRenderingContext2D object; such as:

var context = canvas.getContext("2d");

Call the CanvasRenderingContext2D object for drawing. A picturesque straight line:

//Set the start point and end point of the object

context.moveTo(10,10);

context.lineTo(200,200);

 

The more complete code is given below

<!DOCTYPE html>

<head>

    <meta charset="UTF-8">

    <title>canvas drawing demo</title>

    <style>

        #canvas{

            border: 1px solid #ADACB0;

            display: block;

            margin: 20px auto;

        }

    </style>

</head>

<body>

    <canvas id="MyCanvas" width="300" height="300">

        Your browser does not support canvas

    </canvas>

</body>

<script>

    var canvas = document.getElementById("MyCanvas");

    var context = canvas.getContext("2d");

    //Set the start point and end point of the object

    context.moveTo(10,10);

    context.lineTo(200,200);

    //Set the style

    context.lineWidth = 2; //Line width

    //draw

    context.stroke();

</script>

</html>

The save file name is: CanvasDemo.html, open with a browser, the effect is as follows (my save path D:\HTML5_canvas example):

 

Create Canvas element

Add the canvas element to the HTML5 page. Specify the id, width and height of the element:

<canvas id="myCanvas" width="200" height="100"></canvas>

Tip: The default width and height of canvas is 300*150, and the unit is px.

Example 1 : Create Canvas (Canvas) code

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5Canvas example 1</title>
<style type="text/css">
canvas {     border: 1px solid black; } </style> </head> <body> <!-- [html comment] Set the drawable area of ​​the canvas: width="300" height="300". JavaScript code can access this area. --> <canvas id="tutorial" width="300" height="300"></canvas>






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

Save the file name: CanvasDemo1.html, open with a browser, the effect is as follows (my save path D:\HTML5_canvas example):

 

 

Draw rectangle

In the above example 1, the canvas is blank, so how to draw graphics in it?

First look at canvast provides three methods to draw rectangles:

1. fillRect(x, y, width, height): draw a filled rectangle.

2. strokeRect(x, y, width, height): draw a rectangular border.

3. clearRect(x, y, widh, height): Clear the specified rectangular area, and then this area will become completely transparent.

Note: These 3 methods have the same parameters.

x, y: refers to the coordinates of the upper left corner of the rectangle. (Relative to the origin of canvas coordinates)

width, height: refers to the width and height of the drawn rectangle.

 

Example 2 : Draw two rectangles

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5Canvas示例2</title>
<style type="text/css">
canvas {     border: 1px solid black; } </style> </head> <body> <!--    [html注释] 设置画布的可绘制区域:width="300" height="300" 。JavaScript 代码可以访问该区域。--> <canvas id="tutorial" width="300" height="300"></canvas> <script> function draw(){     var canvas = document.getElementById('tutorial');     if(!canvas.getContext) return;     var ctx = canvas.getContext("2d");     ctx.fillRect (10, 10, 55, 50);       //Draw a rectangle     ctx.fillStyle = "rgb(200,0,0)";















 
    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect (30, 30, 55, 50);
}
draw();

</body>
</html>

Save the file name: CanvasDemo2.html, open with a browser, the effect is as follows:

 

Draw line segment

Methods to be used:

beginPath() creates a new path, once the path is created successfully, the graphics drawing command is directed to the path to generate a path

moveTo(x, y) Move the pen to the specified coordinates (x, y). It is equivalent to setting the coordinates of the starting point of the path.

closePath() After closing the path, the graphics drawing command is redirected to the context

stroke() Draw the outline of the figure through the line

fill() generates a solid graphic by filling the content area of ​​the path

Example 3: Drawing a triangle
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5Canvas example 3</title>
<style type="text/css">
canvas {     border: 1px solid black; } </style> </head> <body> <!-- [html comment] Set the drawable area of ​​the canvas: width="300" height="300". JavaScript code can access this area. --> <canvas id="tutorial" width="300" height="300"></canvas> <script> //JavaScript code function draw(){     var canvas = document.getElementById('tutorial');     if (!canvas.getContext) return;















    ctx.moveTo(50, 50); //Move the pen to the specified coordinates
    ctx.lineTo(200, 50);
    ctx.lineTo(200, 200);
    ctx.closePath(); //Close the path and pull one A straight line from the current point to the starting point of the path. If the current point coincides with the starting point, nothing will be done
    ctx.stroke(); //Draw the path-stroke
}
draw();
</script>
</body>
</html>

Save the file name: CanvasDemo3.html, open with a browser, the effect is as follows:

 

Draw arc

There are two ways to draw arcs:

1. arc(x, y, r, startAngle, endAngle, anticlockwise): Take (x, y) as the center and r as the radius, starting from the arc of startAngle and ending with the arc of endAngle. anticlosewise is a Boolean value, true means counterclockwise, false means clockwise (the default is clockwise).

note:

The degrees here are all radians. Convert the angle to radians: radians=(Math.PI/180)*degrees

0 radians refers to the positive direction of the x-axis.

 

2. arcTo(x1, y1, x2, y2, radius): Draw an arc according to the given control point and radius, and finally connect the two control points with a straight line.

 

Example 4 , drawing arc source code

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5Canvas示例4</title>
<style type="text/css">
canvas {     border: 1px solid black; } </style> </head> <body> <!--    [html注释] 设置画布的可绘制区域:width="300" height="300" 。JavaScript 代码可以访问该区域。--> <canvas id="tutorial" width="300" height="300"></canvas> <script> //JavaScript 代码 function draw(){     var canvas = document.getElementById('tutorial');     if(!canvas.getContext) return;     var ctx = canvas.getContext("2d");     ctx.beginPath(); //Create a new path     //Draw a triangular shape















    ctx.arc(100,100,80,0*Math.PI/180,270*Math.PI/180); //Set the path
    ctx.lineWidth=2; //Set the outline thickness, ctx.strokeStyle="orange"; Outline style ctx .fillStyle='azure';Set the internal filling style
    //ctx.closePath(); //Close the path, it will draw a straight line from the current point to the starting point of the path. If the current point coincides with the starting point, nothing will be done
    ctx.stroke(); //Draw the path-stroke
}
draw();
</script>
</body>
</html>

Save the file name: CanvasDemo4.html, open with a browser, the effect is as follows:

 

The above is only static drawing. The following describes how to draw a drawing dynamically by dragging the mouse.

Realize the pencil function

Canvas cannot draw points. Use lineTo at a very fine granularity, so the naked eye seems to be a smooth curve. First set up two arrays clickX, clickY, and then listen to the series of events of click-move-release of the mouse on the canvas, and write the coordinates of all the points passed in the process into the two arrays just now. After writing, use a method to take out the contents of the array and draw the route just now. The state quantity sPainting is used to mark whether the user is really painting. Four are used: mousedown (mouse down) mouseup (mouse release) mousemove (mouse movement) mouseout (mouse leave). It is easy to understand from the literal meaning, which are when the mouse is pressed, released, moved, and left. Will trigger.

Example 5 , canvas pencil function-drag the mouse to draw pictures dynamically

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5Canvas example 5</title>
<style type="text/css">
canvas {     border: 1px solid black; } </style> </head> <body> <!-- [html comment] Set the drawable area of ​​the canvas: width="600" height="400". JavaScript code can access this area. --> <canvas id="myCanvas" width="600" height="400"></canvas> <script> //JavaScript code var canvas, context,       isPainting,       clickX, clickY, clickDrag;     var mouseDown = function( e){       var mouseX = e.pageX;       var mouseY = e.pageY;       isPainting = true;  












    




    addClick(mouseX, mouseY, false);  
    redraw();  
  }  
  var mouseUp = function(e){  
    isPainting = false;  
    redraw();  
  }  
  var mouseMove = function(e){  
    if(isPainting){  
        var mouseX = e.pageX;  
        var mouseY = e.pageY;  
        addClick(mouseX, mouseY, true);  
        redraw();  
    }  
    
  }  
  var mouseOut = function(e){  
    isPainting = false;  
  }  
    
  function addClick(mouseX, mouseY, isDragging){  
    clickX.push(mouseX);  
    clickY.push(mouseY);  
    clickDrag.push(isDragging);  
  }  
    
  //重绘  
  function redraw(){  
    context.clearRect (0 , 0, canvas.width , canvas.height );  
    context.strokeStyle = "#000000";  
    var numOfPts = clickX.length;  
    for(var i=0; i<numOfPts; i++){  
        context.beginPath();  
        if(clickDrag[i]){  
            context.moveTo(clickX[i-1], clickY[i-1]);  
            context.lineTo(clickX[i], clickY[i]);  
        }else{  
            context.arc(clickX[i], clickY[i], 0.5, 0, 2*Math.PI, true);  
        }  
        context.closePath();  
        context.stroke();  
    }  
  }  
    
  //初始化  
  function init(){  
    canvas = document.getElementById("myCanvas");  
    context = canvas.getContext("2d");  
    isPainting = false;  
    clickX = new Array();  
    clickY = new Array();  
    clickDrag = new Array();  
    //鼠标事件  
    canvas.onmousedown = mouseDown;  
    canvas.onmouseup = mouseUp;  
    canvas.onmousemove = mouseMove;  
    canvas.onmouseout = mouseOut;  
  }  
    
  window.onload = init();  

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

Save the file name: CanvasDemo5.html, open with a browser, the effect is as follows:

 

With the above foundation, further study can reduce the frustration.

Finally, give a code that can change some colors and handwriting thickness, and drag the mouse to draw dynamically.

 

Example 6. You can change some codes of color and handwriting thickness, and drag the mouse to draw a picture dynamically. First, give the effect picture:

code show as below:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>HTML5Canvas example 6</title>
    <script>
        var bot;//Canvas div
        var X,Y,X1,Y1; //Coordinate
        var flag=0;
        var time;//timer ID
        var color=0;//remember the selected color
        var lineW=2;//brush thickness
        var canvas;//create canvas
        var context;//get Context
        var isMouseDown=false;//Record whether the mouse is pressed
 
        window.οnlοad=function(){             //Create canvas             canvas=document.getElementById("can");             //Get context             context=canvas.getContext("2d") ;             bot=document.getElementById("bottom");





            bot.οnmοusedοwn=mouseDownAction;
            bot.οnmοusemοve=mouseMoveAction;
            document.οnmοuseup=mouseUpAction;
        }
 
        /**
         *选中画笔颜色
         */
        function pen_click(num){
            var chk=document.getElementsByTagName("input");
            for(var i=0;i<chk.length;i++){
                if(i==num){
                    chk[i].checked=true;
                    color=i;
                }else {
                    chk[i].checked="";
                }
            }
        }
 
        /**
         * 画笔粗细
         */
        function line_wid(num){             lineW=num;         }         /**          *Mouse down          */         function mouseDownAction(e){             isMouseDown=true;             //Record the position when the mouse is clicked             X = e.offsetX;             Y = e. offsetY;         }         /**          *mouse movement          */         function mouseMoveAction(e){             if(isMouseDown){                 X1= e.offsetX;                 Y1= e.offsetY;                 drowline(X,Y,X1,Y1);                 flag++;             }         }         / **


 









 











 

         *Mouse up
         */
        function mouseUpAction(e){             isMouseDown=false;             flag=0;         }         /**          * Draw          */         function drowline(num1,num2,num3,num4){             //Open a new path             if(flag)                 context.beginPath();             //The initial position of the moving brush             context.moveTo(num1,num2);             context.lineWidth=lineW;             if(color==0){                 context.strokeStyle="red";             }else if(color= =1){                 context.strokeStyle="green";             }else if(color==2){



 















                context.strokeStyle="blue";
            }
            //Move the end position of the brush
            context.lineTo(num3,num4);
            //Start drawing
            context.stroke();
 
            if(flag!=0){                 X=X1;                 Y=Y1 ;             }         }



 
        function clear_pic(){//Clear the canvas
            context.clearRect(0,0,600,400);
        }

    </script>
</head>
<body>
<div id="left">
    <div id="top">
        <div class="top_left"><!-- 画笔颜色选择 -->
            <img src="img/pen_red.gif" style="border: 2px solid transparent" οnclick="pen_click(0)"><input type="checkbox" style="position: absolute;top: 38px;left: 48px" checked οnclick="pen_click(0)">
            <img src="img/pen_green.gif" style="border: 2px solid transparent" οnclick="pen_click(1)"><input type="checkbox" style="position: absolute;top: 38px;left: 95px" οnclick="pen_click(1)">
            <img src="img/pen_blue.gif" style="border: 2px solid transparent" οnclick="pen_click(2)"><input type="checkbox" style="position: absolute;top: 38px;left: 142px" οnclick="pen_click(2)">
        </div>
        <div class="top_right"><!-- 画笔粗细选择 -->
            <img src="img/pen_thin.gif" οnclick="line_wid(2)">
            <img src="img/pen_medium.gif" οnclick="line_wid(4)">&nbsp;&nbsp;&nbsp;
            <img src="img/pen_thick.gif" οnclick="line_wid(8)">
        </div>
    </div>
    <div id="bottom"><!-- 画板 -->
        <canvas id="can" width="600" height="400"></canvas>
    </div>
</div>

<div class="bottom">
    <hr>
    <input type="button" value="清除画布" style="position: absolute;top: 460px;left: 66px"οnclick="clear_pic()">
</div>
</body>

<style>
    
    *{
        margin: 0px;
        padding: 0px;
    }
    #left{
        width: 500px;
        height: 450px;
        float: left;
    }
    .top_left{
        margin-left: 50px;
        float: left;
    }
    .top_right{
        margin-right: 50px;
        float: right;
    }
    #bottom{
        width: 600px;
        height: 400px;
        border: solid 2px coral;
        float: left;
    }

</style>
</html>

Save the file name: CanvasDemo6.html, open it with a browser to try the effect.

Note that in the location where the CanvasDemo6.html file is located, create an img folder containing the following pictures

 

 

Guess you like

Origin blog.csdn.net/cnds123/article/details/112916903