Home > Web Front-end > H5 Tutorial > Detailed explanation of graphic code for HTML5 canvas drawing

Detailed explanation of graphic code for HTML5 canvas drawing

黄舟
Release: 2017-03-25 15:27:37
Original
4305 people have browsed it

HTML5 canvas drawing

HTML5 tag For drawing Detailed explanation of graphic code for HTML5 canvas drawings (via script, usually JavaScript)
However, the element itself has no drawing capabilities (it is just a container for graphics) - you must use scripts to do the actual work. Drawing tasks.
The getContext() method returns an object that provides methods and properties for drawing on the canvas.
This manual provides the complete getContext("2d") object properties and methods available. Used to draw text, lines, rectangles, circles, etc. on the canvas

Browser support
Internet Explorer 9, Firefox, Opera, Chrome and Safari support and its properties and methods.

1. Drawing

In real life, drawing needs to be considered:

Canvas

Pen

1. The thickness of the line;

2. The color of the line;

3. The thickness of the line;

Drawing the line

1. Starting point;

2. End point;

Draw a circle

1. Dot;

2. Radius;

3. Solid or hollow

Draw a rectangle

1. The upper left starting point of the rectangle;

2. The length and width of the rectangle;

Text

1. Font style;

2. Solid or hollow;

Add pictures, etc.

2. Draw picturesAPI

According to drawing needs, canvas is available The followingAPI

##canvasMain properties and methods


canvas
APIColor, Style and Shadow Properties and Methods

Method Description
save() Save the state of the current environment
restore() Return the previously saved path status and attributes
createEvent()
getContext() Returns an object indicating the necessary information to access the drawing function API
##toDataURL() Return canvasURL of the Detailed explanation of graphic code for HTML5 canvas drawing
Properties Description
fillStyle Sets or returns the color, gradient, or mode used to fill the painting
strokeStyle Sets or returns the color, gradient, or mode used for strokes
shadowColor Sets or returns the color used for shadows
shadowBlur Set or return the blur level used for shadows
shadowOffsetX Set or return the horizontal distance of the shadow from the shape
shadowOffsetY Set or return The vertical distance of the shadow from the shape
Method Description
createLinearGradient() Create a linear gradient (used on canvas content)
createPattern() Repeat the specified element in the specified direction
createRadialGradient() Create a radial/circular gradient (used on canvas content)
addColorStop() Specify the color and stop position in the gradient object


Canvas’ API-Line Style Properties and Methods

##Set or return the end point style of the line##lineJoinlineWidthmiterLimit


Canvas API-rectangular method

##Properties Description
lineCap
Set or return the corner type created when two lines intersect
Set or Returns the current line width
Sets or returns the maximum miter length
##rect()Create a rectanglefillRect()Draw a "filled" rectanglestrokeRect()Draw a rectangle (no fill)clearRect()Clears the specified pixels within the given rectangle


Canvas API-Path Method

# #Method Description
方法 描述
fill() Fill the current drawing (path)
stroke() Draw a defined path
beginPath() Start a path, or reset the current path
moveTo() Move the path to the specified point in the canvas without creating a line
closePath() Create from the current point Path back to starting point
lineTo() Add a new point, create from that point to the end Line at specified point
clip() Clips an area of ​​any shape and size from the original canvas
quadraticCurveTo() Create quadratic Bezier curve
bezierCurveTo() Create a cubic Bezier curve
##arc() Create arcs/curves (for creating circles or partial circles)
arcTo() Create an arc/curve between two tangent lines
isPointInPath() Returns a Boolean value if the specified point is located in the current path


Canvas API-Conversion Method

##transform()Replaces the current transformation matrix of the drawingsetTransform()Reset the current transformation to the identity matrix. Then run transform()#


Canvas API-Text properties and methods

Method Description
scale () Scale the current drawing to a larger or smaller size
rotate() Rotate the current drawing
##translate() Remap (0, 0) Position
##fontSet or return the current font attribute of the text contenttextAlignSet or return The current alignment of text contenttextBaselineSets or returns the current text baseline used when drawing text

##Properties Description
Method Description
fillText() Draw "filled" text on the canvas
strokeText() Draw text on canvas (no padding)
measureText() Returns an object containing the specified text width

##Canvas’ API-Image drawing method


Canvas API-Pixel operation methods and properties

Method Description
drawImage() Draw an Detailed explanation of graphic code for HTML5 canvas drawing, canvas or video to the canvas Chrome does not support
##widthReturn the width of the ImageData objectheightReturn the height of the ImageData objectdataReturns an object containing the Detailed explanation of graphic code for HTML5 canvas drawing data of the specified ImageData object

##Properties Description
##Method Description
createImageData() Create a new, blank ImageData object
getImageData() Returns the ImageData object, which copies the pixel data for the specified rectangle on the canvas
putImageData() Put the Detailed explanation of graphic code for HTML5 canvas drawing data (from the specified ImageData object) back to the canvas

Canvas API-Image composition properties

##globalAlphaglobalCompositeOperation


三.Canvas simple drawing

3.1canvas APIExercise

<!doctype html><html>
    <head></head>
    <body>
        <canvas width="500" height="800" style="background:yellow"  id="canvas">
            您的浏览器当前版本不支持canvas标签        
            </canvas>
        <script>
            //获取画布DOM  还不可以操作
            var canvas=document.getElementById(&#39;canvas&#39;);            
            //alert(canvas);
            //设置绘图环境
            var cxt=canvas.getContext(&#39;2d&#39;);            
            //alert(cxt);
            
            //画一条线段。
                //开启新路径                
                cxt.beginPath();                
                //设定画笔的宽度                
                cxt.lineWidth=10;                
                //设置画笔的颜色                
                cxt.strokeStyle="#ff9900";                
                //设定笔触的位置                
                cxt.moveTo(20,20);                
                //设置移动的方式                
                cxt.lineTo(100,20);                
                //画线                
                cxt.stroke();                
                //封闭路径                
                cxt.closePath();            
                //画一个空心圆形  
                凡是路径图形必须先开始路径,画完图之后必须结束路径
                //开始新路径                
                cxt.beginPath();                
                //重新设置画笔                
                cxt.lineWidth=3;
                cxt.strokeStyle="green";
                cxt.arc(200,200,50,0,360,false);
                cxt.stroke();                
                //封闭新路径                
                cxt.closePath();            
                //画一个实心圆形                
                cxt.beginPath();                
                //设置填充的颜色                
                cxt.fillStyle="rgb(255,0,0)";
                cxt.arc(200,100,50,0,360,false);
                cxt.fill();
                cxt.stroke();
                cxt.closePath();            
                //画一个矩形                
                cxt.beginPath();
                cxt.rect(300,20,100,100);
                cxt.stroke();
                cxt.closePath();                
                //其他方法 建议使用此方式                
                cxt.strokeRect(300,150,100,100)                
                //实心矩形                
                cxt.beginPath();
                cxt.rect(300,270,100,100);
                cxt.fill();
                cxt.closePath();                
                //其他方法 建议使用此方式                
                cxt.fillRect(300,390,100,100);            
                //设置文字                
                cxt.font="40px 宋体";//css font属性                
                cxt.fillText("jingwhale",20,300);                
                //将笔触设置为1像素                
                cxt.lineWidth=1;
                cxt.strokeText("jingwhale",20,350);            
                //画图 把一幅图片画到画布中  注意webkit内核的浏览器 chrome和猎豹不支持
                var img =new Image();
                img.src="xiaomm.jpg";
                cxt.drawImage(img,20,370,230,306);            
                //画一个三角形                
                cxt.beginPath();                
                //移动至开始点                
                cxt.moveTo(300,500);
                cxt.lineTo(300,600);
                cxt.lineTo(400,550);
                cxt.closePath();//填充或者画路径需要先闭合路径再画                
                cxt.stroke();                
                //实心三角形                
                cxt.beginPath();                
                //移动至开始点                
                cxt.moveTo(300,600);
                cxt.lineTo(300,700);
                
                cxt.lineTo(400,650);
                cxt.closePath();
                cxt.fill();            
                //旋转图片 图片
                //设置旋转环境                
                cxt.save();                    
                //在异次元空间重置0,0点的位置                    
                cxt.translate(20,20);                
                //图片/形状旋转
                    //设置旋转角度  参数是弧度  角度 0-360 弧度=角度*Math.PI/180                    
                    cxt.rotate(-30*Math.PI/180);
                    //旋转一个线段                    
                    cxt.lineWidth=10;
                    cxt.beginPath();
                    cxt.moveTo(0,0);
                    cxt.lineTo(20,100);
                    cxt.stroke();
                    cxt.closePath();                
                    //将旋转之后的元素放回原画布                
                    cxt.restore();                
                    //过程不可颠倒 先设置00点在旋转角度,然后画图
                
            //旋转图片                
            cxt.save();
                cxt.translate(20,370);
                cxt.rotate(-10*Math.PI/180);
                var img =new Image();
                img.src="xiaomm.jpg";
                cxt.drawImage(img,0,0,230,306);
                cxt.restore();            
                
        </script>
        
    </body></html>
Copy after login

3.2Drawing process

1. Set and get the canvas DOM;

2. Set the drawing environment
var cxt=canvas.getContext('2d');
3. Open a new path

cxt.beginPath();

4.Set the width of the brush
cxt.lineWidth=10;
5.Set the color of the brush
cxt.strokeStyle= "#ff9900";

6. Draw according to API

7. Close the path
cxt.closePath();

3.3 canvas operation -Planet Movement

//获取canvas绘图环境
            var context = document.getElementById(&#39;canvas&#39;).getContext(&#39;2d&#39;);
            var time = 0;
            //星球轨道
            function drawTrack(){
                for(var i = 0; i < 8; i++){
                    //开始路径
                    context.beginPath();
                    context.arc(500,500,(i+1)*50,0,360,false);
                    //关闭路径
                    context.closePath();
                    context.strokeStyle = &#39;#fff&#39;;
                    context.stroke();
                }
            }
            //执行以下此函数,画出各星球的轨道
            drawTrack();

            //星球  星球对象的构造方法 实例化后能画出所有的星球
            function Star(x,y,radius,sColor,eColor,cycle){
            //星球需要的哪些属性
                //星球的坐标点
                this.x = x;
                this.y = y;
                //星球的半径
                this.radius = radius;
                //星球的颜色
                this.sColor = sColor;
                this.eColor = eColor;
                //公转周期
                this.cycle = cycle;

                //绘画出星球
                this.draw = function(){  //异次元空间进行绘画
                    context.save();
                    //重设0,0坐标点
                    context.translate(500,500);
                    //设置旋转角度
                    context.rotate(time*360/this.cycle*Math.PI/180);

                    context.beginPath();
                    context.arc(this.x,this.y,this.radius,0,360,false);
                    context.closePath();
                    //星球的填充色(径向渐变 开始色和结束色)
                    this.color = context.createRadialGradient(this.x,this.y,0,this.x,this.y,this.radius);
                    this.color.addColorStop(0,this.sColor);
                    this.color.addColorStop(1,this.eColor);
                    context.fillStyle = this.color;
                    context.fill();
                    context.restore();

                    time +=1;
                }
                
            }

            //各星球构造方法 从star中继承
            function Sun(){
                Star.call(this,0,0,20,&#39;#f00&#39;,&#39;#f90&#39;,0);
            }
            function Mercury(){
                Star.call(this,0,-50,10,&#39;#A69697&#39;,&#39;#5C3E40&#39;,87.70);
            }
            function Venus(){
                Star.call(this,0,-100,10,&#39;#C4BBAC&#39;,&#39;#1F1315&#39;,224.701);
            }
            function Earth(){
                Star.call(this,0,-150,10,&#39;#78B1E8&#39;,&#39;#050C12&#39;,365.2422);
            }
            function Mars(){
                Star.call(this,0,-200,10,&#39;#CEC9B6&#39;,&#39;#76422D&#39;,686.98);
            }
            function Jupiter(){
                Star.call(this,0,-250,10,&#39;#C0A48E&#39;,&#39;#322222&#39;,4332.589);
            }
            function Saturn(){
                Star.call(this,0,-300,10,&#39;#F7F9E3&#39;,&#39;#5C4533&#39;,10759.5);
            }
            function Uranus(){
                Star.call(this,0,-350,10,&#39;#A7E1E5&#39;,&#39;#19243A&#39;,30799.095);
            }
            function Neptune(){
                Star.call(this,0,-400,10,&#39;#0661B2&#39;,&#39;#1E3B73&#39;,164.8*365);
            }

            //各星球对象的实例化
            var sun = new Sun();
            var water = new Mercury();
            var gold = new Venus();
            var diqiu = new Earth();
            var fire = new Mars();
            var wood = new Jupiter();
            var soil = new Saturn();
            var sky = new Uranus();
            var sea = new Neptune();

            function move(){
                //清除画布
                context.clearRect(0,0,1000,1000);
                //重新绘制一遍轨道
                drawTrack();

                sun.draw();
                water.draw();
                gold.draw();
                diqiu.draw();
                fire.draw();
                wood.draw();
                soil.draw();
                sky.draw();
                sea.draw();
            }
            
            //星球围绕太阳运动起来
            setInterval(move,100);
Copy after login

Demonstration

IV. Canvas Drawing Example-Webpage Drawing

Detailed explanation of graphic code for HTML5 canvas drawing

1. Drawing board function analysis

Ritual area (save, clear)
Tool area (shapes and tools)
Attribute setting area (color and line Width)
Drawing area (canvas tag)

2. Technical requirements analysis

Page layout-> ;HTML5 tag
Page beautification->CSS2
Function settings->Javascript programming
Canvas API->Attribute settings, line drawing, writing, drawing, canvas operations (clearing, obtaining canvas information),
Download->php download (JS cannot operate local files)

3. Draw a simple canvas

Mouse click When
Prepare the starting point moveTo(), set the flag
When the mouse moves
Judge the flag, the value is true to draw the picture, false does not draw the picture
Specify the path lineTo() when moving, and draw the stroke ()
Leave or raise the mouse
Clear the flag

4. Complex online drawing board

Get the corresponding element object
Set click state
Set trigger function
Color attribute settings
Line width attribute settings
Drawing shape settings
Tool specification

5.html Structural part:

Detailed explanation of graphic code for HTML5 canvas drawing

Detailed explanation of graphic code for HTML5 canvas drawing

6. Drawing technical points:

Entire drawing Controlled by mouseevent


Mouse down event-》mousedown
Mouse move event-》mousemove
Mouse up event-》 mouseup

//鼠标按下的时候-》设置开始点canvas.onmousedown=function(evt){
Copy after login
//鼠标移动的时候-》不同的绘图(获取鼠标的位置)canvas.onmousemove=function(evt){}
Copy after login
//鼠标抬起的时候结束绘图canvas.onmouseup=function(){
Copy after login
## Property Description
Set or return the current alpha or transparency value of the drawing
Set or return the new Detailed explanation of graphic code for HTML5 canvas drawing How to draw to an existing Detailed explanation of graphic code for HTML5 canvas drawing

The above is the detailed content of Detailed explanation of graphic code for HTML5 canvas drawing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template