Graphics library in the front end

graphics library

SVG

The concept and introduction of SVG

1. SVG refers to scalable vector graphics (Scalable Vector Graphics), used to define vector-based graphics for the network, using the XML format to define graphics. SVG images can be scaled up or resized without loss of graphic quality and are a World Wide Web Consortium standard.

2. SVG is integrated with W3C standards such as DOM and XSL. In January 2003, SVG 1.1 was established as a W3C standard. The advantages of using SVG over other image formats are the following:

  • Can be created, read and modified by a wide variety of tools
  • Smaller size and better compression than JPEG and GIF images
  • Can be printed with high quality at any resolution and can be enlarged without loss of image quality
  • Text in images is optional and can also be searched (great for maps), indexed, scripted
  • Can run with Java technology, has open standards, and is pure XML

3. SVG file, save with .svg suffix:

<?xml version="1.0" standalone="no"?>  
    // standalone="no"意味着SVG文档会引用一个外部文件——这里是DTD文件
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">   
//该DTD位于W3C,含有所有允许的SVG元素。
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">  
//根元素,width 和 height 属性可设置此 SVG 文档的宽度和高度,version定义所使用的SVG版本,xmlns定义SVG命名空间
    <circle cx="200" cy="100" r="50" stroke="red" stroke-width="2" fill="green"/>
</svg>

4. SVG reference method

Method 1: Import SVG files with img

<img src="1svg.svg"/>   

Method 2: Use styles to make SVG the background

<div style="height:200px; width:200px; background:url(1svg.svg) no-repeat"></div>

Method 3: Import SVG with a frame

<iframe src="1svg.svg"></iframe>

Method 4: Write svg in html page (HTML5 technology, namespace must have)

<div id="div1">  
    <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
        <circle cx="100" cy="100" r="40" fill="red" />
    </svg>
</div>

img When you set the border, the border is a part of the model. After setting the border, the width of the box will increase by 2 times the border width.

When svg sets the border, the size of the graphic will only increase by half of the border width. That is to say, the border width is set to 10px, but in fact the 5px border expands outward, and the 5px border expands to the content area.

5. The settings for SVG drawing can be set with attributes or css styles:

  • fill fill color: fill="white"/fill:white;
  • fill-opacity fill transparency: fill-opacity="0.5"/fill-opacity:0.5;
  • stroke border color: stroke="black"/stroke:black;
  • stroke-width border width: stroke-width="5"/stroke-width:5;
  • stroke-opacity border transparency: stroke-opacity="0.5"/stroke-opacity:0.5;
  • opacity The transparent value of the entire element: opacity="0.5"/opacity:0.5;
SVG drawing style
SVG graphics drawing

1. SVG graphics drawing syntax:

  • circle (drawing a circle) - attribute parameters: cx (X-axis coordinates of the center of the circle), cy (Y-axis coordinates of the center of the circle), r (radius)
<circle cx="" cy="" r="" fill="" />  
//cx和cy默认值为0
  • ellipse (ellipse) - attribute parameters: cx (X-axis coordinates of the center of the circle), cy (Y-axis coordinates of the center of the circle), rx (radius of the X-axis), ry (radius of the Y-axis)
 <ellipse cx="" cy="" rx="" ry="" fill="" />  
 //rx和ry的值相等时即是圆形                            
  • rect (rounded rectangle) - attribute parameters: width (width), height (height), x (X-axis coordinates of the upper left corner), y (Y-axis coordinates of the upper left corner), rx (X-axis radius of the rounded corner), ry ( The Y-axis radius of the fillet, if omitted, it is a perfect circle with a radius of rx)

     <rect x="" y="" width="" height="" rx="" ry="" stroke="" stroke-width="" />        //注意:边框的宽度同时向内外延伸
    
  • line (drawing a line, the line is a border that cannot be filled with fill color) —— attribute parameters: x1 (X-axis coordinates of the starting point), y1 (Y-axis coordinates of the starting point), x2 (X-axis coordinates of the end point), y2 (Y-axis coordinates of the end point)

     <line x1="" y1="" x2="" y2="" stroke="" stroke-width="" />  
     //stroke默认白色                      
    
  • polyline (polyline) - attribute parameter: points (vertex setting), fill='transparent' must be set to remove the fill

    <polyline points="" fill="transparent" stroke="" />  
    //points的值为坐标对,如:10,10 10,50 50,50 50,100 100,100 100,150
    

    polygon (polygon) - attribute parameters: same as above, do not remove the padding

    <polyline points="" fill="red"/>               
    
SVG text

text (text) - attribute parameters: x (text X-axis coordinates), y (text Y-axis coordinates), font-size (font size), font-family (text style), text-anchor (alignment point, coordinates at Where is the text middle/start/end)

<text x="" y="" text-anchor="" fill="" >文字内容</text>   
//文字用填充色
SVG image

image (image)——attribute parameters: x (image X-axis coordinates), y (image Y-axis coordinates), width (image width), height (image height), xlink:href (image address)

<image x="" y="" width="" height="" xlink:href=""/>  
//这里图片不会变形,会按照width和height最小比例进行缩放
SVG path

path (path, single tag): path is the most powerful of the SVG basic shapes, and it can create all shapes including other basic shapes. Such as rectangles, circles, ellipses, polylines, polygons, and curves such as Bezier curves and quadratic curves. Use the attribute d to define the path point, which is a sequence of commands + parameters. Commands include:

  • M(moveto)/L(lineto): The brush moves to a certain point/the brush draws from the previous point to the current point
  • H(horizontal lineto)/V(vertical lineto): draw horizontal line/draw vertical line
  • C(curveto)/S(smooth curveto): cubic Bezier curve/abbreviated cubic Bezier curve command
  • Q(quadratic Bézier curve)/T(smooth quadratic Bézier curveto): Quadratic Bezier curve/abbreviated quadratic Bezier curve command
  • A(elliptical Arc): Draw an arc
  • Z (closepath): closed path (drawn from the current position to the starting point)
<path d="M50 50 L150 150 L50 150" fill="red"/>  
//大写的命令代表绝对位置(参照左上0,0点的位置),填充时无需设置Z闭合
<path d="M50 150 h100 v-50 Z" stroke="red" stroke-width="2" fill="transparent"/>  
//小写的命令代表相对位置(相对于上个点增加或减少多少)

Overly complex graphs are often converted into path codes through images: Convert URLs

SVG filter
SVG blur and shadow filters

1. Before we learned about css filters, we can modify the effect of elements through the value of filter. SVG can also set filters. Not only can it be used in SVG, some can even be used in HTML with css filters. Filters in SVG are defined in the filter element, which has a required id attribute that identifies the filter and then points to the filter to use. There are many SVG filters, and some commonly used examples are used to illustrate.

2.feGaussianBlur: used to create blur effects

<filter id="f1" x="0" y="0">  
    //定义滤镜,获得f1标识,在SVG的filter属性或元素css的filter样式中使用
    <feGaussianBlur in="SourceGraphic" stdDeviation="15" />  
        //in属性决定创建效果;stdDeviation决定了模糊量
</filter>
<rect width="90" height="90" stroke="green" stroke-width="3" fill="yellow" filter="url(#f1)" />

3.eOffset: used to create a shadow effect, take an SVG graphic (image or element) and offset it in the xy plane, then superimpose it on the original image with feBlend, if you need to blur the shadow, set feGaussianBlur also, use feColorMatrix Change the color of the shadow towards black

<filter id="f1" x="0" y="0" width="200%" height="200%">
    <feOffset result="offOut" in="SourceGraphic" dx="20" dy="20" />   
        //dx和dy,x轴和y轴偏移距离,将in的值改成SourceAlpha可以变成黑色影子(无论图形什么颜色),如果设置feColorMatrix可以让颜色向接近黑色变化
    <feColorMatrix result="matrixOut" in="offOut" type="matrix" values="0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 1 0" />
    <feGaussianBlur result="blurOut" in="matrixOut" stdDeviation="10" />
    <feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
</filter>
<rect width="90" height="90" stroke="green" stroke-width="3" fill="yellow" filter="url(#f1)" />
                    
SVG graduated filter

1.linearGradient: Used to define a linear gradient, use stop to define the color point of the linear gradient. Linear gradients can be defined as horizontal, vertical or angular gradients: when y1 and y2 are equal and x1 and x2 are different, a horizontal gradient is created; when x1 and x2 are equal and y1 and y2 are different, a vertical gradient is created; when x1 and x2 When different and y1 and y2 are different, an angular gradient will be created.

<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">  
    // x1,x2,y1,y2 属性定义渐变的开始和结束位置
    <stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />  
        //offset为该颜色点在开始到结束的位置
    <stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />  
        //style的stop-color和stop-opacity用于设置颜色和透明度
</linearGradient>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" />
<text fill="#ffffff" font-size="45" font-family="Verdana" x="150" y="86">SVG</text>

2.radialGradient: used to define the radial gradient, use stop to define the color point of the linear gradient. cx, cy is the center of the outermost layer (determines the shape, generally 50%, 50% is the center point), fx, fy is the center of the innermost layer (the gradient center point, to be set in the graph)

<radialGradient id="grad1" cx="50%" cy="50%" r="50%" fx="50%" fy="90%">
    <stop offset="0%" style="stop-color:red;stop-opacity:1" />  
        //offset的值决定了梯度,0%即最内层
    <stop offset="50%" style="stop-color:green;stop-opacity:0.5" />
    <stop offset="100%" style="stop-color:blue;stop-opacity:1" />  
        //100%即最外层
</radialGradient>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="yellow" />
<text fill="url(#grad1)" font-size="55" font-family="Verdana" x="140" y="90" >SVG</text>
                    
SVG warping and grouping

1. The SVG transformation is similar to the CSS3 transformation, except that it is written on the transform attribute of the SVG tag, but relative to the 0,0 point of the SVG root element, and the unit cannot be added.

  • translate: displacement
  <rect x="0" y="0" width="100" height="100" transform="translate(30,40)" />
  • rotate: rotate

    <rect x="-50" y="-50" width="100" height="100" transform="translate(100 100) rotate(45)" />  
    //为了让其以中心点旋转,我们需要把0,0点设置在其中心点上,然后位移到需要的位置,再旋转             
    
  • skewX() and skewY(): oblique cut

    <rect x="0" y="0" width="100" height="100" transform="skewX(30) skewY(30)" />
    
  • scale: scaling and flipping

    <rect x="0" y="0" width="100" height="100" transform="translate(100 100) scale(-0.5)" />   
    //负值也是翻转,但是由于中心点在0,0点,一样需要设置中心点防止位移
    

2.g (grouping tag): It is a container tag used to combine elements, so that a group of elements can be controlled at the same time, such as when performing deformation:

<g style="cursor:pointer" transform="translate(100 100) rotate(45) scale(-1,1)"> 
    <circle cx="0" cy="0" r="40" fill="yellow" stroke="red" stroke-width="3" /> 
    <text x="0" y="8" font-size="20" text-anchor="middle"> 新卓越</text> 
</g> 
SVG animation
SVG Basic Animation

1. SVG elements are different from HTML elements. There is no way to use positioning or margins to change the position, but you can use the animation style of css3 to perform animation. In addition, SVG also provides animate tags to set animations. Note that this requires the SVG editor is set to double markup, making animate its child element

2. Important properties of animate:

  • attributeName - the name of the attribute that needs to be animated;

  • from/to——the initial value/end value of the attribute; values——each setting point of the animation, and the two values ​​are consistent with the writing effect of from and to;

  • dur——animation duration; repeatCount——the number of repetitions, the default is once, and indefinite is an infinite loop

    <rect width="100" height="100" x="10" y="10">
     <animate attributeName="x" values="10;150;10" dur="4s" repeatCount="indefinite"/>  
     //values设置3个值且最后一个值等于第一个值比较适合循环
    </rect>
    <rect width="100" height="100" x="10" y="120">
     <animate attributeName="width" from="100" to="240" dur="4s" repeatCount="3"/>
    </rect>
    

3. If you want to animate more attributes of the element, just add more animate elements to the element.

<rect width="100" height="100" x="10" y="10" fill="red">
    <animate attributeName="rx" values="0;25;0" dur="4s" repeatCount="indefinite" />
    <animate attributeName="fill" values="red;blue;green;red" dur="4s" repeatCount="indefinite" />
</rect>
SVG deformation animation

1. When our animation needs to do rotation and other effects, the animate mark is obviously not enough, and it is time for animateTransform to appear.

2. Important properties of animateTransform:

  • attributeName——The name of the attribute that needs to be animated, only "transform"; type——The type of deformation animation, rotate (rotation), scale (zoom), translate (displacement), skewX (X-axis direction offset), skewY (Y-axis direction offset);
  • from/to——each has three parameters, which are the start/end angle, the X-axis start/end coordinates, and the Y-axis start/end coordinates;
  • dur——animation duration; repeatCount——the number of repetitions, the default is once, and indefinite is an infinite loop

3. Set animateTransform in the tag to perform deformation animation:

<rect x="50" y="50" width="30" height="40" fill="blue" stroke="black" stroke-width="1" transform="rotation">  
    <animateTransform attributeName="transform" begin="0s" dur="5s" type="rotate" from="0 65 70" to="360 65 70" repeatCount="indefinite" />  
        //form和to的第二个第三个值起始就是旋转的中心点
</rect>

4. If you want text tags to also have animation effects, you can use the g tag to wrap all the tags that you want to perform animation

<g>
    <rect x="50" y="50" width="30" height="40" fill="blue" stroke="black" stroke-width="1" transform="rotation"/>
    <text x="50" y="70" text-anchor="center" fill="white">文字</text>
    <animateTransform attributeName="transform" begin="0s" dur="5s" type="rotate" from="0 65 70" to="360 65 70" repeatCount="indefinite" />
</g>
SVG path animation

1. If we want the element to perform animation according to the route we designed, we need to use the animateMotion tag, and the path is defined in a way similar to path

2. Important properties of animateMotion:

  • path——same as the d attribute of the path tag, setting an animation path;
  • dur——animation duration; repeatCount——the number of repetitions, the default is once, and indefinite is an infinite loop
  • rotate——rotation mode, the default value is no rotation, auto rotates along the inner circle, auto-reverse rotates along the outer circle

3. Use animateMotion to set the animation. For the convenience of viewing, we will draw the corresponding path together:

<path d="M 250,80 H 50 Q 30,80 30,50 Q 30,20 50,20 H 250 Q 280,20,280,50 Q 280,80,250,80ZM 250,80 H 50 Q 30,80 30,50 Q 30,20 50,20 H 250 Q 280,20,280,50 Q 280,80,250,80Z" stroke="red" fill="transparent"/>
<rect x="0" y="0" width="20" height="20" fill="blue" stroke="black" stroke-width="1">
    <animateMotion path="M 250,80 H 50 Q 30,80 30,50 Q 30,20 50,20 H 250 Q 280,20,280,50 Q 280,80,250,80Z" dur="3s" repeatCount="indefinite" rotate="auto">
</rect>

4. Even we can use mpath to directly treat a path graph as a path

<path id="path1" d="M100,250 C 100,50 400,50 400,250" fill="none" stroke="blue" stroke-width="2"/>
<path d="M-25,-12.5 L25,-12.5 L 0,-87.5 z" fill="yellow" stroke="red" stroke-width="7.06">
    <animateMotion dur="6s" repeatCount="indefinite" rotate="auto">
        <mpath xlink:href="#path1"/>
    </animateMotion>
</path>
JS manipulation of SVG
<div style="width:500px;height:500px">
        <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
        </svg>
</div>
<script>
        var oSVG=document.getElementsByTagName('svg')[0];
        var oCircle=createSVG('circle',{
    
    
            "cx":"120",
            "cy":"120",
            "r":"50",
            "fill":"blue"
        });
        oCircle.onclick=function(){
    
    
            console.log('yes');
        }
        oSVG.appendChild(oCircle);
        function createSVG(tagName,option){
    
    
            var sXmls="http://www.w3.org/2000/svg";
            var obj=document.createElementNS(sXmls,tagName);
            for(var attr in option){
    
    
                obj.setAttribute(attr,option[attr]);
            }
            return obj;
        }
</script>
practise
//绘制六边形
<div class="div1">
        <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
            <path d="M100 30 L140 60 L140 100 L100 130 L60 100 L60 60 Z" stroke="black" stroke-width="3px" fill="transparent"></path>
        </svg>
 </div>
//屏幕解锁静态效果
<div class="div1">
        <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
            <circle cx="40" cy="40" r="25" fill="transparent" stroke="black" stroke-width="4px"/>
            <circle cx="120" cy="40" r="25" fill="transparent" stroke="black" stroke-width="4px"/>
            <circle cx="200" cy="40" r="25" fill="transparent" stroke="black" stroke-width="4px"/>

            <circle cx="40" cy="120" r="25" fill="transparent" stroke="black" stroke-width="4px"/>
            <circle cx="120" cy="120" r="25" fill="transparent" stroke="black" stroke-width="4px"/>
            <circle cx="200" cy="120" r="25" fill="transparent" stroke="black" stroke-width="4px"/>

            <circle cx="40" cy="200" r="25" fill="transparent" stroke="black" stroke-width="4px"/>
            <circle cx="120" cy="200" r="25" fill="transparent" stroke="black" stroke-width="4px"/>
            <circle cx="200" cy="200" r="25" fill="transparent" stroke="black" stroke-width="4px"/>
        </svg>
</div>
//靶子效果
<div class="div1">
        <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
            <g  transform="translate(160 160)">
                <circle cx="0" cy="0" r="140" fill="red"/>
                <circle cx="0" cy="0" r="120" fill="#fee4d3"/>
                <circle cx="0" cy="0" r="100" fill="red"/>
                <circle cx="0" cy="0" r="80" fill="#fee4d3"/>
                <circle cx="0" cy="0" r="60" fill="red"/>
                <circle cx="0" cy="0" r="40" fill="#fee4d3"/>
                <circle cx="0" cy="0" r="20" fill="red"/>
//方式一
                <path d="M0 -160 L0 160 Z"  stroke="black" stroke-width="2" fill="transparent"></path>
                <path d="M-160 0 L160 0 Z"  stroke="black" stroke-width="2" fill="transparent"></path>
//方式二
                <!-- <line x1="0" y1="-180" x2="0" y2="180" stroke="black" stroke-width="2" /> 
                <line x1="-180" y1="0" x2="180" y2="0" stroke="black" stroke-width="2" />  -->
            </g>
        </svg>
</div>

Canvas

The concept of Canvas

1. Canvas is a new tag provided by HTML5. It does not have the ability to paint itself, it is just a canvas and a container. The drawing capability is based on the CanvasRenderingContext2D object returned by html5's getContext("2d") (3d needs to use webgl).

2. When will canvas be used

  • Games: Canvas is more three-dimensional and more compact than Flash in terms of web-based image display, and is more powerful in terms of fluency and cross-platform.
  • Visual data. Data charting: For example: Baidu's echart
  • Banner advertisement: It was also completed by Flash before. In the era of smart phones, HTML5 technology can play a greater role in banner advertisements.
  • Simulator/Remote Computer Control/Graphic Editor: These functions that cannot be controlled on the Web can be realized with canvas.
  • Other content that can be embedded in a website (live pages, special effects): graphics, audio, video, and many other elements that can better integrate with the web and do not require any plug-ins.
  • Complete canvas mobile app

3. Differences from SVG

  • Svg does not depend on resolution and supports event handlers. It is most suitable for applications with large rendering areas (such as Google Maps). High complexity will slow down rendering speed (any application that uses DOM excessively is not fast), not suitable for gaming applications. ;
  • Canvas is resolution-dependent, does not support event handlers, has weak text rendering capabilities, can save the resulting image in .png or .jpg format, and is most suitable for image-intensive games, where many objects will be redrawn frequently

4. Create a canvas tag, which looks similar to the img tag, except that it only has two optional attributes, width and height, without src and alt attributes. When the width and height attributes are not set, the default width is 300 and height is 150, and the unit is px.

You can also use css properties to set the width and height, but if the width and height properties are inconsistent with the initial ratio, it will zoom.

It is recommended never to use css properties to set the width and height of the canvas unless scaling is really required.

<canvas id="c1" width="400" height="400"></canvas>
//设置绘图环境
var oC = document.getElementById('c1'); //获得画布
var oCG = oC.getContext('2d'); //注意:2d小写
Canvas drawing style
Canvas basic method

The starting point of the canvas element is the upper left corner (0,0), x increases to the right, and y increases downward. All elements are positioned relative to the origin. Drawing a canvas requires drawing a path on a 2d object (it will not be drawn), and then calling stroke or fill to draw it

oCG.fillStyle = color;   
//设置填充颜色
oCG.strokeStyle = color;   
//设置描边颜色
oCG.lineCap = "round";  
//端点样式:butt(方形,默认)、round(圆角)、square(多出宽的一半)
oCG.lineJoin = "round";  
//边界连接点样式:miter(直角,默认)、round(圆角)、bevel(斜角)
oCG.moveTo(x,y);  
//移动画笔到x,y点
oCG.lineTo(x,y);  
//绘制直线路径(从画笔上一个的位置绘制到x,y点)
oCG.beginPath();   
//开始绘制新路径(以区分与之前的路径)
oCG.closePath();   
//闭合该次绘制的最后位置和初始位置
oCG.stroke();    
//描边,以线的方式画出绘制的路径
oCG.fill();    
//填充,将闭合的路径内填充颜色

Notice:

The line width of oCG.lineWidth="1" is the same as that of oCG.lineWidth="2", but the former line is lighter than the latter line width. This is because: oCG.lineWidth="1"; oCG.lineTo(20,20); oCG.stroke(); will extend 0.5px from (20,20) to the left and 0.5px to the right It is said that the left and right pixels of the line are 19.5px and 20.5px, but since the pixel is an integer of 1px, it will actually stretch 1px to the left and 1px to the right at (20,20), and the color will become lighter. The left and right pixels are 19px and 21px, and the line width is 2px.

oCG.lineWidth="2" is the normal result.

oCG.beginPath() means to redraw another path from here, and will not redraw the previous path, while OCG.closePath() means to close the path. The two methods seem to be antonyms, but in fact they are just two different uses, not opposite ones.

Canvas graphics drawing
//绘制矩形:x,y是矩形左上角坐标,width和height是尺寸
oCG.rect(x, y, width, height); 
oCG.strokeRect(x, y, width, height);  
//直接用描边画出来
oCG.fillRect(x, y, width, height);  
//直接用填充画出来
oCG.clearRect(x, y, width, height);  
//清除该矩形内的绘制的内容,相当于橡皮擦

//绘制圆弧:圆心到最右边点是 0 度,顺时针方向弧度增大,弧度和角度的转换公式:rad = deg*Math.PI/180
oCG.arc(x, y, r, sAngle, eAngel, anticlockwise); 
//x,y是圆心坐标,r是半径,sAngle是起始弧度,eAngel是结束弧度,注意是弧度,anticlockwise是否是逆时针(true 是逆时针,false:顺时针)
oCG.arcTo(x1, y1, x2, y2, r);  
//用起始点到x1,y1和x1,y1到x2,y2作为切线,用r作为半径画弧
canvas text

To draw text, use fillStyle to set fillText to draw the filled font; use strokeStyle to set strokeText to draw the stroked font:

oCG.font = "18px bold 黑体";  
// 设置字体
oCG.fillStyle = "#ff0";   
// 设置颜色
oCG.textAlign = "center";  
// 设置水平对齐方式
oCG.textBaseline = "middle";  
// 设置垂直对齐方式
oCG.fillText("要写的文字", 100, 100);  
// 绘制文字(参数:内容,指定位置x,y坐标)

textAlign: start (default): the text starts at the specified position; end: the text ends at the specified position; center: the center of the text is placed at the specified position; left: the text is left aligned; right: the text is right aligned.
textBaseline: alphabetic (default): the text baseline is the alphabetic baseline; top: the text baseline is the top of the four-line grid; hanging: the text baseline is the hanging baseline; middle: the text baseline is the middle of the four-line grid; ideographic: the text baseline is the ideogram Baseline; bottom: The text baseline is the bottom of the four-line grid.

canvas image

Draw a picture: This method can also draw a video or another canvas, just replace the picture object with a video/canvas object

var img = new Image(); //如图片未在dom中需先创建img对象
img.src = '图片路径';
img.onload = function (){
    
      //图片加载成功后绘制图片
    oCG.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
}

img is the picture object to be drawn, sx, sy, width, and height are slices of the original picture, if not set, the whole picture is used to draw, x and y are the distance from 0, 0 points, width and height are the drawing size (if missing The province is equal to the size of the original image)

//举个例子
oCG.drawImage(img,300,100,550,220,50,50,400,120);
//从原图(300,100)位置开始,截取宽550高220的尺寸。在canvas里(50,50)开始绘制图,大小为400*120
Canvas draws the background

Set the background image: same as the image, the image not in the dom needs to be loaded first

var img = new Image();
img.src = '图片路径';
img.onload = function (){
    
      //图片加载成功后绘制背景图
    oCG.fillStyle = oCG.createPattern(this,'repeat'); 
    //用图片来绘制填充图像,平铺方式(repeat、repeat-x、repeat-y、no-repeat)
    oCG.fillRect(0,0,300,300);  //设置完成后可以用此填充图来绘制任何形状
}
Save Settings

Saving and restoring the configuration state (save and restore): It is an essential operation when drawing complex graphics, similar to the function scope of js, the settings within a save and restore range only take effect internally:

    oCG.save();                  // 保存默认状态
    oCG.fillStyle = 'red'       
    oCG.fillRect(15, 15, 120, 120);  

        oCG.save();                  // 再次保存当前状态
        oCG.fillStyle = '#FFF'       
        oCG.fillRect(30, 30, 90, 90);  
        oCG.restore();               // 重新加载之前的颜色状态,退出这次的save()操作

    oCG.fillRect(45, 45, 60, 60);  
    oCG.restore();               // 加载默认颜色配置,退出这次的save()操作

oCG.fillRect(60, 60, 30, 30);   // 使用加载的配置绘制一个矩形
Morphing and Compositing

1. Like css, canvas deformation is also the scaling, displacement and rotation of the graphics to be drawn, but the canvas deformation is the entire canvas, once set, all new elements drawn subsequently will be affected. To make the deformation only take effect on the drawing that needs to be deformed, the save and restore methods must be used.

  • translate displacement: move the origin of the canvas to the specified position
oCG.translate(x, y);  //x轴和y轴的偏移值   
  • Scale zoom: scale the graphics to be drawn in the canvas
oCG.scale(x, y);   //x轴和y轴的缩放因子      
  • rotate rotation: rotate the coordinate axis
oCG.rotate(angle);   //正值为顺时针,参数值为弧度 

2. When we draw multiple graphics, there will definitely be overlaps. The default is that the one drawn later will cover the original one. We can change the composited appearance by setting the value of the composite (globalCompositeOperation)

oCG.globalCompositeOperation = type;

The value of type: source-over (default, the new image covers the original image), source-in (only the new image of the overlapping part is displayed), source-out (only the new image of the non-overlapping part is displayed), source-atop (the overlapping part is displayed part of the new image and all the original image), destination-over (the original image overwrites the new image), destination-in (only the original image of the overlapping part is displayed), destination-out (only the original image of the non-overlapping part is displayed), destination- atop (display the original image and all new images of the overlapping part), lighter (the same as the default, the overlapping part is superimposed), darken (the same as the default, the overlapping part is highlighted), lighten (the same as the default, the overlapping part is darkened), xor (same as the default By default, the overlapping part is transparent), copy (only keep the new image)

small example

//绘制一个正方形
<canvas width="500" height="500"></canvas>
    <script>
        var oC=document.getElementsByTagName('canvas')[0];
        var oCG=oC.getContext('2d');
		oCG.fillRect(100,100,150,150);
    </script>
//绘制一个旋转45度的正方形
<canvas width="500" height="500"></canvas>
    <script>
        var oC=document.getElementsByTagName('canvas')[0];
        var oCG=oC.getContext('2d');
      	oCG.translate(175,175);
		//将画布的原点移动到(175,175)的位置也就是原本正方形的中心点
		oCG.rotate(45*Math.PI/180);
		//将所作图形按照原点顺时针旋转45度
		oCG.fillRect(-75,-75,150,150);
		//既然原本的(175,175)充当了画布原点,那么原本的正方形的左上角点(100,100)就变成了(-75,-75)
    </script>
//要求:绘制一个红色小方块,不断旋转的同时由小变大再由大变小
 <canvas width="500" height="500"></canvas>
    <script>
        var oC=document.getElementsByTagName('canvas')[0];
        var oCG=oC.getContext('2d');
        var scal=1;
        var rota=1;
        var flag=true;
		//var change=0.01;
		//oCG.globalCompositeOperation = "copy";
		//有了这句可以代替oCG.clearRect()
        setInterval(function(){
    
    
            oCG.clearRect(0,0,oC.width,oC.height);
            oCG.save();
            oCG.translate(250,250);
            //方法一
            if(scal<2&&flag){
    
    
                scal+=0.01;
            }else{
    
    
                scal-=0.01;
                flag=false;
                if(scal<=0.1){
    
    
                    scal+=0.01;
                    flag=true;
                }
            }
            //方法二
            // if(scal>2){
    
    
            //    change=-0.01;
            //}else if(scal<=0){
    
    
            //    change=0.01;
            //}
            //scal+=change;
            
            oCG.scale(scal,scal);
            oCG.rotate((rota++)*Math.PI/180);
            oCG.fillStyle="#f40";
            oCG.fillRect(-75,-75,150,150);
            oCG.restore();
        },17)
    </script>
Canvas save picture

1. We can generate or save the drawn canvas as a picture, and we need to put the generated base64 in the src attribute of img or the href attribute of a

2.toDataURL: Output the content drawn by the canvas into base64 content, and the parameter is the image format (image/png, image/jpeg)

method one

<canvas width="500" height="500"></canvas>
<a href="">aa</a>    
<script>
    var oC=document.getElementsByTagName('canvas')[0];
    var oCG=oC.getContext('2d');
    oCG.fillStyle="red";
    oCG.arc(150,150,100,0,360);
    oCG.fill();
	var oA = document.querySelector("a");
    oA.href = oC.toDataURL("image/png");
    oA.download = "p.png";  //download为下载图片的名字
</script>

way two

 <canvas width="500" height="500"></canvas>
  <img src="" /> 
    <script>
        var oC=document.getElementsByTagName('canvas')[0];
        var img = document.querySelector("img");
        var oCG=oC.getContext('2d');
        oCG.fillStyle="red";
        oCG.arc(150,150,100,0,360);
        oCG.fill();
        img.src = oC.toDataURL("image/png");  //注意toDataURL是画布方法,不是2d绘图环境的方法
    </script>

3. With the html2canvas.js library, we can convert an html part into a canvas, and then generate a picture or download it

 <style>
        table,td{
    
    
            border: 1px #000 solid;
            background-color: orange;
        }
        td{
    
    
            width: 120px;
            height: 60px;
        }
 </style>
 <table cellspacing="0">
        <tbody>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <a href="">aa</a>
        </tbody>
</table>
<script src="../canvastoimg.js"></script>
<script>
        var oTable=document.getElementsByTagName('table')[0];
        var oA=document.getElementsByTagName('a')[0];
        new html2canvas(oTable).then(canvas=>{
    
    
            let oImg=new Image();
            oImg.src=canvas.toDataURL('image/png');
            document.body.appendChild(oImg);
            oA.href=canvas.toDataURL('image/png');
            oA.download="my.png";
        })
</script>
Canvas animation

1. The animation of the canvas is not that the drawn graphics move, but the animation is realized by constantly drawing and clearing.

2. Steps to realize the animation frame:

  • Empty canvas: Before drawing each frame of animation, you need to clear the canvas with clearRect()
  • Save the state of the canvas: If the state of the canvas (color, moving the origin of coordinates, etc.) will be changed during the drawing process, and if it is the original state when drawing each frame, you need to save the state of the canvas
  • Draw animation graphics: draw the animation frames you need
  • Restore the canvas state: restore the previously saved canvas state after drawing a frame

3. Below we draw a frame, and then use the timer to repeat the above process: methods such as setInterval()/setTimeout()/requestAnimationFrame(), setTimeout() and requestAnimationFrame() need recursion, and then let each frame of the picture There are some changes to achieve animation effects, such as:

var x = 0,y = 0;
var timer = setInterval(function (){
    
    
    oCG.clearRect(0,0,oC.offsetWidth,oC.offsetHeight);
    oCG.fillRect(x++,y++,100,100);
    if(x>oC.offsetWidth-100){
    
    
        clearInterval(timer);
    }
},50)
practise

electronic clock effect

A few notes:

  • For time: (walk around 360 degrees for 24 hours)

    The hour hand moves 30 degrees in 1 hour

    For the minute hand, it walks 360 degrees in 1 hour and walks 60 minutes. For the hour hand, it walks 30 degrees in 1 hour and also walks 60 minutes. Then the hour hand walks (30/60) degrees in 1 minute.

  • For points: (walk 360 degrees for 60 minutes)

    The minute hand moves for one minute and the second hand moves for 60 seconds. 60 minutes is a full circle, so 6 degrees are gone in 1 minute. That is to say, 6 degrees in 60 seconds. Then it can be concluded that 1 minute is 6 degrees; 1 second is 0.1 degrees.

    For the second hand, it walks 360 degrees for 60 seconds in 1 minute, and for the minute hand, it also walks 60 seconds for 6 degrees in 1 minute, then the minute hand walks (6/60) degrees in 1 second.

  • Then the reason for the angle of the hour hand per minute (Hours 30+Minutes/2-90) instead of (Hours 30+Minutes/2) is that the 12 o'clock direction is regarded as the 0 degree position according to the clock, which can be written as (Hours 30+Minutes /2); However, since the 12 o'clock direction of the canvas is -90 degrees, the actual calculation formula is (Hours 30+Minutes/2-90).

  • oCG.arc(200,200,50,(Hours*30+Minutes/2-90) Math.PI/180,(Hours 30+Minutes/2-90)*Math.PI/180,false); This starting angle and The graph drawn by the end angle is a straight line with a biased angle.

//电子时钟效果
<canvas width="400" height="400" class="myCanvas"></canvas>
<script>
        var oC=document.getElementsByClassName('myCanvas')[0];
        var oCG=oC.getContext('2d');
        oCG.strokeStyle="black";
        var Hours=0;
        var Minutes=0;
        var Seconds=0;
        for(var i=0;i<60;++i){
    
    
            oCG.beginPath();
            oCG.moveTo(200,200);
            oCG.arc(200,200,150,(i*6)*Math.PI/180,((i+1)*6)*Math.PI/180,false);
            oCG.stroke();
        }
        oCG.beginPath();
        oCG.fillStyle="white";
        oCG.arc(200,200,140,0,360*Math.PI/180,false);
        oCG.fill();

        oCG.strokeStyle="orange";
        for(var i=0;i<12;++i){
    
    
            oCG.beginPath();
            oCG.moveTo(200,200);
            oCG.arc(200,200,150,(i*30)*Math.PI/180,(i*30)*Math.PI/180,false);
            oCG.stroke();
        }
        oCG.beginPath();
        oCG.fillStyle="white";
        oCG.arc(200,200,130,0,360*Math.PI/180,false);
        //少写oCG.fill()就会有一些不同之处
        oCG.fill();

        oCG.beginPath();
        oCG.fillStyle="black";
        oCG.arc(200,200,5,0,360*Math.PI/180,false);
        oCG.fill();
   
        setInterval(function(){
    
    
            init();
        },1000);

        function init(){
    
    
            oCG.clearRect(100,100,200,200);
            //不加这里的oCG.beginPath()会出现问题。
            oCG.beginPath();
            oCG.fillStyle="black";
            oCG.arc(200,200,5,0,360*Math.PI/180,false);
            oCG.fill();
            var time=new Date();
            Hours=time.getHours();
            Minutes=time.getMinutes();
            Seconds=time.getSeconds();

             //下面的这三个oCG.beginPath()也很重要。如果不写可能会出现时针中有一根红色的细线,分针中也有根红色的细线。
            oCG.beginPath();
            oCG.strokeStyle="gray";
            oCG.lineWidth="5";
            oCG.moveTo(200,200);
            oCG.arc(200,200,50,(Hours*30+Minutes/2-90)*Math.PI/180,(Hours*30+Minutes/2-90)*Math.PI/180,false);
            oCG.stroke();
            
            oCG.beginPath();
            oCG.strokeStyle="black";
            oCG.lineWidth="3";
            oCG.moveTo(200,200);
            oCG.arc(200,200,80,(Minutes*6+Seconds/10-90)*Math.PI/180,(Minutes*6+Seconds/10-90)*Math.PI/180,false);
            oCG.stroke();

            oCG.beginPath();
            oCG.strokeStyle="#f40";
            oCG.lineWidth="2";
            oCG.moveTo(200,200);
            oCG.arc(200,200,100,(Seconds*6-90)*Math.PI/180,(Seconds*6-90)*Math.PI/180,false);
            oCG.stroke();
        }
        init();
</script>
//绘制视频
<video src="./Intermission-Walk-in_512kb.mp4" id="video" controls></video>
<canvas class="myCanvas"></canvas>
<script>
        var oC=document.getElementsByClassName('myCanvas')[0];
        var oCG=oC.getContext('2d');
		var video=document.getElementsByTagName('video')[0];
        //必须是window.onload,此外video.onloadedmetadata也是可以的
        window.onload = function (){
    
      //图片加载成功后绘制图片
            oC.width=video.videoWidth;
            oC.height=video.videoHeight;
            setInterval(function(){
    
    
                oCG.clearRect(0,0,oC.offsetWidth,oC.offsetHeight);
                oCG.drawImage(video,0,0);
            },16.67);
        }
</script>
//自制画笔功能
<canvas width="400" height="300" class="myCanvas"></canvas>
<br/>
<input type="text" placeholder="请输入画笔的宽度" value="3"/>
<span>画笔的颜色:</span><input type="color" />
<script>
        var oC=document.getElementsByClassName('myCanvas')[0];
        var oCG = oC.getContext('2d'); 
        var oWidth=document.getElementsByTagName('input')[0];
        var oColor=document.getElementsByTagName('input')[1];
        oCG.lineWidth=oWidth.value;
        oCG.strokeStyle=oColor.value;
        oC.onmousedown=function(e){
    
    
            oCG.beginPath();
            oCG.moveTo(e.pageX-oC.offsetLeft,e.pageY-oC.offsetTop);
            document.onmousemove=function(ev){
    
    
                oCG.lineTo(ev.pageX-oC.offsetLeft,ev.pageY-oC.offsetTop);
                oCG.stroke();
            }  
            document.onmouseup=function(){
    
    
                oCG.closePath();
                document.onmouseup=document.onmousemove=null;
            } 
        }
        oWidth.onchange=function(){
    
    
            oCG.lineWidth=oWidth.value;
        }
        oColor.onchange=function(){
    
    
            oCG.strokeStyle=oColor.value;
        }
</script>

jCanvas

The concept of jCanvas

1.js has the jQuery library. If the canvas is not encapsulated, it will be very troublesome to write, and it cannot be operated like an object. jCanvas is a free and open source HTML5 Canvas API based on jQuery. It lets you use the native Canvas API and do a lot more. You can also use native Canvas API methods with jCanvas, the draw() method can be used like this. You can also use your own method combined with extend() function to extend the functionality of jCanvas.

2. jCanvas needs to rely on jQuery to work properly, so make sure to import the jQuery file:

<script src="js/jquery.min.js"></script>
<script src="js/jcanvas.js"></script>                    
jCanvas drawing style
draw rectangle

drawRect() method

$("canvas").drawRect({
    
    
    fillStyle: 'steelblue',   //设置填充色
    strokeStyle: 'blue',     //设置边框色
    strokeWidth: 4,         //设置边框宽
    x: 150,        //设置基点x轴位置
    y: 100,        //设置基点y轴位置
    fromCenter: false,      //基点是否为中心点(false为矩形左上角)
    width: 200,   //设置矩形宽
    height: 100   //设置矩形高
});
Draw arcs and circles

drawArc() method

$("canvas").drawArc({
    
    
    fillStyle: 'steelblue', 
    strokeStyle: 'blue',
    strokeWidth: 4,
    x: 300,  y: 100,      //设置圆心x/y轴位置
    radius: 50,   //设置半径
    ccw:true,     //是否逆时针(false默认值为顺时针)
    start: 0, end: 200     //设置起点/终点角度(0为12点位置)
});
chain operation

Since the drawing object is a jQ object, it can be chained like jQ to draw a smiling face:

$("canvas").drawArc({
    
      // draw the face
    fillStyle: 'yellow', 
    strokeStyle: '#333', 
    strokeWidth: 4,
    x: 300, 
    y: 100, 
    radius: 80
}).drawArc({
    
     // draw the left eye
    fillStyle: '#333', 
    strokeStyle: '#333',
    x: 265, 
    y: 85,
    radius: 5
}).drawArc({
    
     // draw the right eye
    fillStyle: '#333', 
    strokeStyle: '#333',
    x: 335,
    y: 85, 
    radius: 5
}).drawArc({
    
     // draw the smile
    strokeStyle: '#333',
    strokeWidth: 4, 
    x: 300, y: 120, 
    radius: 30, 
    start: 110, 
    end: 250
});
draw lines

drawLine()

$("canvas").drawLine({
    
    
    strokeStyle: 'steelblue',
    strokeWidth: 10,
    rounded: true,  //设置边界连接点是否为圆角
    closed: true,   //设置是否闭合路径
    x1: 100, y1: 28,  //设置第一个点坐标......
    x2: 50, y2: 200,
    x3: 300, y3: 200,
    x4: 200, y4: 109
});
draw text

drawText()

$("canvas").drawText({
    
    
    text: 'Canvas is fun',    //文字内容
    fontFamily: 'cursive',   //字体
    fontSize: 40,          //字体大小
    x: 290, y: 150,
    fillStyle: 'lightblue',
    strokeStyle: 'blue',
    strokeWidth: 1
});
draw path

drawPath() method. You can draw arrows the same way you draw lines and curves, but you have to provide some arrow-specific properties

$("canvas").drawPath({
    
    
    strokeStyle: '#000', 
    strokeWidth: 4, 
    x: 10,   
    y: 10,
    //以(10,10)为canvas画布的原点
    p1: {
    
       //当type="line"时其实就相当于绘制线条
        type: 'line',   //路径类型(常用的line-线、arc-圆弧、quadratic-二次曲线、vector-矢量)
        x1: 100, y1: 100, x2: 200, y2: 100 
    },
});
//绘制箭头
$("canvas").drawPath({
    
    
    strokeStyle: '#000', 
    strokeWidth: 4, 
    x: 10, 
    y: 10,
    p1: {
    
       //第二部分
        type: 'line', 
        startArrow: false,     //是否有一个箭头画在路径的开始点。
        endArrow: true,   //是否有一个箭头画在路径的结束点
        arrowRadius: 25,   //箭头的每个尖端的长度
        arrowAngle: 90,    //箭头两个尖端的夹角
        x1: 100, 
        y1: 100, 
        x2: 290,
        y2: 100 
    },
    p2: {
    
       //第三部分
        type: 'line', 
        startArrow: false, 
        endArrow: true, 
        arrowRadius: 25, 
        arrowAngle: 90, 
        x1: 100, 
        y1: 100, 
        x2: 100, 
        y2: 250 
    }
});
draw pictures

drawImage() method

$('canvas').drawImage({
    
    
    source: $('#fish')[0],  //绘制DOM已经存在的图片,或用'imgs/cat.jpg'绘制未加载的图片
    x: 50, 
    y: 50, 
    fromCenter: false,
    width: 100, 
    height: 100,  //图片大小
    shadowColor: '#222',  //阴影颜色
    shadowBlur: 3,  //模糊距离
    rotate: 40,   //旋转角度
    load (){
    
      //未加载的图片可以设置
        //加载图片后的代码,
    }
});

This method is originally drawn after the image is loaded successfully.

create layers

The addLayer() method or the layer property adds a layer to the canvas.

$('canvas').drawRect({
    
    
    layer: true,  //创建一个图层后绘制图形
    name: 'myBox',  //用来检索图层、删除图层或变动图层
    fillStyle: '#585', 
    x: 100, 
    y: 100, 
    width: 100, 
    height: 50
});
                    
jCanvas events and animations

1. You can bind any number of jCanvas events on any jCanvas layer. jCanvas supports mouse events and touch events Events will be used in conjunction with the layer API.

2. Methods that support events: drawRect(), drawArc(), drawEllipse(), drawLine(), drawQuadratic(), drawBezier(), drawVector(), drawGraph(), drawPolygon(), , drawImage(), drawText( )

3. Supported events: click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, dragstart, drag, dragstop, touchstart, touchend, touchmove

4. Cooperate with animateLayer to perform animation effects

$('canvas').drawRect({
    
    
    layer: true,  
    //绘制图层
    fillStyle: '#6c0', 
    x: 100, 
    y: 100, 
    width: 100,
    height: 80,
    click (layer) {
    
      
        //layer为图层对象
        $(this).animateLayer(layer,{
    
     
            rotate : layer.rotate+144
        },400)  
    },  //参数:执行动画的图层对象、变化样式和动画时间
    animatestart (layer){
    
    },  
    //动画开始时,要运行的代码
    animate (layer, fx){
    
    },  
    //动画相关属性的动画fx(prop属性为执行动画的样式、start为初始值、now为当前值、end为结束值)的每个帧上运行这些代码
    animateend (layer){
    
    }   
    //动画结束时,要运行的代码
});
                    
jCanvas drag layer

1. Set the attribute draggable to true to make a layer draggable.

$('canvas').drawArc({
    
    
    layer: true, 
    draggable: true, 
    fillStyle: '#36c',
    x: 150, 
    y: 150, 
    radius: 50
}).drawRect({
    
    
    layer: true, 
    draggable: true, 
    fillStyle: '#6c1', 
    x: 100, 
    y: 100,
    width: 100, 
    height: 100
});

2. Drag event: Provide callback functions for various drag events by defining dragstart, drag, dragstop and dragcancel.

$('canvas').drawArc({
    
    
    layer: true, 
    draggable: true,
    fillStyle: '#36c',
    x: 150, 
    y: 150,  
    radius: 50,
    groups: ['shapes'],  
    //设置图层组,设置该值的图层即为同一组
    dragGroups: ['shapes'],  
    //拖曳编组,当图层被拖曳时,同一编组中所有其它图层都会被拖动。
    dragstart (layer) {
    
     }, 
    // 在拖曳开始时要运行的代码
    drag (layer) {
    
     }, 
    // 当正在拖曳时要运行的代码
    dragstop (layer) {
    
     }, 
	// 在停止拖曳时要运行的代码
    dragcancel (layer) {
    
     } 
	// 在把一个图层拖出画布时要运行的代码(拖拽过程中鼠标离开画布)
}).drawRect({
    
    
    layer: true, 
    draggable: true,
    fillStyle: '#6c1', 
    x: 100, 
    y: 100, 
    width: 100, h
    eight: 100,
    groups: ['shapes'], 
    dragGroups: ['shapes'] //设置与上面相同的组和拖拽编组
});
practise
//制作一个不断有不同颜色的圆圈有不透明变为透明的效果
   <canvas width="500" height="500"></canvas>
   <script src="../jquery.js"></script>
   <script src="./jcanvas.js"></script>
   <script>
       var index=0;
       setInterval(function(){
    
    
           index++;
        $('canvas').drawArc({
    
    
            layer:true,
            name:'circle'+index,                   				fillStyle:`rgb(${
      
      Math.random()*255},${
      
      Math.random()*255},${
      
      Math.random()*255})`,
            x: Math.random()*$('canvas')[0].offsetWidth,  
            y: Math.random()*$('canvas')[0].offsetHeight,      
            radius: 5,   
            ccw:true,    
            start: 0, 
            end:360,
            anmateend(layer){
    
    
                $('canvas').removeLayer(layer.name);
            }    
        }).animateLayer('circle'+index,{
    
     
            opacity:0,
            radius:50
        },900)  
       },90)
   </script>

ECharts data visualization

The concept of ECharts

The purpose of data visualization is to convey and communicate information clearly and effectively by means of graphics, convert data from numbers to graphics, and better reveal data laws. ECharts , an open source visualization library implemented using JavaScript, can run smoothly on PCs and mobile devices, compatible with most current browsers (IE8/9/10/11, Chrome, Firefox, Safari, etc.), and relies on vector graphics at the bottom The library ZRender provides intuitive, interactive and highly customizable data visualization charts.

ECharts usage
  • Download and import the echarts.js file
  • Prepare a DOM container with size
  • Initialize echarts instance object
  • Specify configuration items and data (option)
  • Assign the set configuration items to the echarts instance object
<script src="echarts.min.js"></script>
<div class="box"></div>  
//设置容器(必须有大小)
var myChart = echarts.init(document.querySelector(".box"));  
//得到echarts实例对象
var option = {
    
     
    //指定配置项和数据
    //配置code
 };  
myChart.setOption(option); 
//将配置项赋予echarts实例对象
Configuration of ECharts

The option configuration object contains many attributes that need to be configured:

  • title: title. Set the icon title through the text attribute (string format)
  • tooltip: Tooltip component. Set the trigger method through the trigger attribute: 'item' - data item graphic trigger, mainly used in charts without category axes such as scatter charts and pie charts; 'axis' - coordinate axis trigger, mainly used in histograms, broken lines used in charts etc. that will use the category axis; 'none' - do not trigger
  • legend: legend component. Set all legend items through the data attribute (array format)
  • toolbox: toolbox component. The feature attribute is used to define the toolbox function (object format, such as setting saveAsImage:{} for saving pictures)
  • grid: grid - part of the coordinate system. The left/right/bottom properties determine the distance from the coordinate system to the left, right, and bottom of the container (percentage string). The containLabel attribute determines whether to display tick marks (boolean value format)
  • xAxis: Abscissa. Use the type attribute to control the axis type: 'value' - value axis; 'category' - category axis, must also set data to set category data; 'time' - time axis; 'log' - logarithmic axis. The data attribute sets the specific data (array format) of the category axis. The boundaryGap property sets the data to be in the point (true)/on the point (false).
  • yAxis: vertical coordinate. ditto
  • series: series chart type, the value is an array. Each item is an object corresponding to the chart type of each legend, and the properties in this object are: name——legend name; type——legend type ('line': line chart; 'bar': histogram; 'pie': Pie chart; 'scatter': scatter plot; 'radar': radar chart; 'tree': tree map; 'map': map; 'graph': relationship graph); stack——if set and given the same value Then the data will be stacked (not crossed); data: specific data (array)
  • color: graphics color, the value is an array
ECharts introduces the official website instance

1. First find the similar examples we need on the official website, introduce them into the HTML page, and customize icons according to requirements. Since each instance needs to initialize the echarts instance object and settings, it is necessary to use an immediate execution function to prevent variable pollution.

2. Customize the chart effect: modify the chart content and style according to our needs, find the setting content of the instance, and modify it according to the configuration properties (for more detailed settings, please refer to the configuration item manual on the official website )

3. The chart adapts to the size of the browser

window.onresize = function (){
    
    
    myChart.resize();
}
practise

The difference between chart.js and Echarts (Baidu)

  • charts.js is more flexible, requires more grammatical knowledge, and is slow to start
  • Echarts is not very flexible, you can use the ready-made demo and modify the style. Start fast.
//做一个学习前端的Echarts图
<style>
    .box{
    
    
        width: 600px;
        height: 500px;
    }
</style>
 <div class="box"></div>
<script src="https://cdn.bootcss.com/echarts/3.6.2/echarts.min.js"></script>
<script>
    var myChart = echarts.init(document.querySelector(".box"));
    var option={
    
    
        title: {
    
    
            text: '前端学习组成',
            subtext: '纵使风吹',
            left: 'center',
            bottom:'0%'
        },
        tooltip: {
    
    
            trigger: 'item'
        },
        legend: {
    
    
            orient: 'vertical',
            left: 'left',
        },
        series: [
            {
    
    
                name: '组成部分',
                type: 'pie',
                radius: '60%',
                data: [
                    {
    
    value: 0.1, name: 'HTML和CSS'},
                    {
    
    value: 0.1, name: 'HTML5和CSS3'},
                    {
    
    value: 0.3, name: 'JavaScript'},
                    {
    
    value: 0.02, name: 'webpack'},
                    {
    
    value: 0.02, name: 'Git'},
                    {
    
    value: 0.05, name: 'ES6'},
                    {
    
    value: 0.03, name: 'JQuery'},
                    {
    
    value: 0.03, name: '移动端'},
                    {
    
    value: 0.15, name: 'React'},
                    {
    
    value: 0.1, name: 'VUE'},
                    {
    
    value: 0.1, name: '项目实战'},
                ],
                emphasis: {
    
    
                    itemStyle: {
    
    
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    }
    myChart.setOption(option); 
</script>

as the picture shows:

insert image description here

Guess you like

Origin blog.csdn.net/qq_44875145/article/details/115247589