Two of canvas knowledge points

Source: Internet
Author: User
Tags foreach base64 cos extend sin

1. Add an array of map methods:

        
        /* * The map method is defined on Array.prototype, so all arrays can access the
        * Syntax: array. Map (callback function)
        * Function: Receive the return value of the callback function, together constitute a new array returned.
        * */

        var arr = [1,2,3,4,5];

        var newArr = Arr.map (function (val, I, arr) {
            return val * 5-i;
        });

        Console.log (NEWARR);

2.canvas is state-based:

        
        /* * Canvas is based on status:
        * strokestyle = ' red ';
        * Strokestyle = ' blue ';
        * The main strokestyle changes, then all the drawing methods associated with the stroke will be affected.
        * *
      /For example:
          <canvas id= "CVS" width= "height=" ></canvas>
    <script>
    var cvs = document.getElementById (' CVS ');
    var ctx = Cvs.getcontext (' 2d ');

    Ctx.strokestyle = ' Blue ';
    Ctx.strokerect (10,10,50,50);

    Ctx.strokestyle = ' red '; To block this sentence, the two rectangles are blue, and the second one turns red
    ctx.strokerect (50,50,50,50);
    </script>

3. After drawing the content on the canvas, use the Todataurl method to convert the canvas content into a base64 encoded image, and try to replace the canvas label with the printed content to see the effect

        Convert the contents of the canvas into a base64 encoded image
        Console.log (cvs.todataurl (' image/png '));

        /*·
        * Base64 encoded Image application:
        * If a website has a small number of smaller images, you can consider using Base64 encoding directly.
        * */

4. Drawing arcs
The main thing is to understand where the starting angle and the ending angle are in the ctx.arc, clockwise or counterclockwise.

    <canvas id= "CVS" width= "$" height= "></canvas>" <script> var cvs = Document.geteleme
        Ntbyid (' CVS ');

        var ctx = Cvs.getcontext (' 2d '); /* * ARC (Draw path) * CTX.ARC (center x axis coordinate, center y coordinate, radius, start arc, end point Radian, whether to draw counterclockwise (optional)) * The Arc method will draw a path line from the end of the path to the beginning of the arc first.
        。
        * The direction of the start, end, and radian determine the size of the arc together.
        * *///convert angle to radians function Angletoradian (angle) {return math.pi/180 * angle;
        }//Draw an arc clockwise to see clearly where is 90 degrees where is 270 degrees clockwise Oh, don't be mistaken ...
        Ctx.arc (+, +, Angletoradian (+), Angletoradian (+), false);

        Ctx.stroke ();
        Draw an arc ctx.beginpath () counterclockwise;
        Ctx.arc (max, +, Angletoradian, Angletoradian (+), true);

        Ctx.stroke ();
        A round ctx.beginpath ();
        Ctx.arc (Angletoradian), Angletoradian (360));

        Ctx.stroke (); /* Draw Fan: * 1, first set the path starting point to center * 2, ARC * 3, closed path
        * */Ctx.beginpath (); Ctx.moveto (250, 250);
        The default is clockwise Ctx.arc ((+), Angletoradian, Angletoradian (180));
        Ctx.closepath ();

    Ctx.stroke ();
 </script>

5. Ask for the maximum value of a set of numbers, using the call and apply method (for the following explanation to pave the way ...) )

    var Nummax = Math.max (2,3,4,6,8,9);

    Use the call method
    var num = Math.max.call (null, (2,3,4,6,8,9));
    var numarr = [2,3,4,6,8,9] with apply method;
    var num = Math.max.apply (Null,numarr);

    Console.log (num);

6. Draw hollow words, solid characters, and their respective reference points on the canvas

    <canvas id= "CVS" width= "$" height= "></canvas>"
    <script>
        var cvs = document.getElementById (' CVS ');
        var ctx = Cvs.getcontext (' 2d ');
        /* * Set Text properties
        * Ctx.font = same as CSS syntax.
        * Note: This font size must be set with units, which supports all representations of CSS.
        * Note: Setting the font size individually does not take effect, you must add an extra attribute style.
        * */

        Ctx.font = ' 2rem Microsoft ya Black ';
        /
        * * Draw Stroke Text:
        * ctx.stroketext (text, reference x-axis coordinates, reference y-coordinate, limit the maximum length of text (optional))
        * *
        /Ctx.stroketext (' I am the hollow font stroketext ', (+);

        /
         * * Draw Fill text:
         * ctx.filltext (text, reference x-axis coordinates, reference y-coordinate, limit the maximum length of text (optional))
         * */
        Ctx.filltext (' I am a solid word filltext ' , (+);


        Draw the reference point of the hollow text
        ctx.beginpath ();
        Ctx.arc (4, 0, Math.PI * 2);
        Ctx.stroke ();

        Draws the reference point of the solid text
        ctx.beginpath ();
        Ctx.arc (4, 0, Math.PI * 2);
        Ctx.fill ();
    </script>

The reference point and baseline on the 7.canvas word together determine the position of the word

    <canvas id= "CVS" width= "$" height= "></canvas>"
    <script>
        var cvs = document.getElementById (' CVS ');
        var ctx = Cvs.getcontext (' 2d ');

        Ctx.font = ' 2rem Microsoft ya Black ';
        /* * Set the level of text to its way:
        * ctx.textalign = ' left | | start ', ' Right ' | | end ', ' center '
        default value is start.
        * *
        /* * Set the vertical way of text:
        * ctx.textbaseline = ' top ', ' bottom ', ' Middle ', ' alphabetic ', ' hanging ', ' Ideographic '
        * Default value is alphabetic.
        *
       /////With reference point as axis (0,0), the x-axis is the baseline
        //textalign indicates the reference point on which side of the word (left and right)
        ctx.textalign = ' ieft ';

        Textbaseline indicates the baseline on which side of the word (upper and lower)
        ctx.textbaseline = ' bottom ';
        Ctx.filltext (' position depends on reference point and Baseline ', +--);

        Draw the reference point of the text
        Ctx.beginpath ();
        Ctx.arc (4, 0, Math.PI * 2);
        Ctx.fill ();
    </script>

8. How to use sine cosine function to find the coordinates of a point on a circle.
In the normal coordinate system we are right x forward, positive y direction upward, angle counterclockwise.
On our canvas, the angle is clockwise, the right is 0 degrees, is the x axis positive direction, the vertical downward is 90 degrees, is the y-axis positive method, so the formula still applies.

Assuming that the coordinate of the center is (A, b), then the equation of the circle is (x-a) ^2+ (y-b) ^2=r^2 according to the
equation can find the coordinates of each point on the circle, the known angle m, the coordinates of the point on the Circle are: (r*cosm+a,r*sinm+b)

9. With so many bedding on top, let's draw a pie chart with the following shape:

Pie_chart.js (Function (w) {//convert angle to radians function Angletoradian (angle) {return math.pi/180 * angle
    ;
            }//Mixed inheritance function extend (O1, O2) {for (var key in O2) {//Only O2 own property will be copied to O1
            if (O2.hasownproperty (key)) {o1[key] = o2[key]; }}}/* * Constrcutor {Pipe} pie chart constructor * param {x:number} center x axis coordinates * param {y:number} Center y coordinate * param {r:number} circle Radius * param {Data:array} plot data required for pie chart * */function Pipe (x, Y, r, data)
        {this.x = x;
        This.y = y;
        THIS.R = R;

        This.data = data;
    A set of colors this.colors = [' orange ', ' orchid ', ' palegoldenrod ', ' palegreen ', ' paleturquoise ', ' Peru ', ' Pink '];
            }//To the prototype extension method extend (Pipe.prototype, {//Draw pie chart draw:function () {//Save this on the outside

            var = this;
The sum of the data var num = 0;            This.data.forEach (function (obj) {num + = Obj.val;

            });

            A data value occupies an angle of var baseangle = 360/num;
                Suppose you start with a sector var that starts at 0 and ends with 0, startangle = 0, Endangle = 0, Lineangle = 0,

            LineX, Liney; Draw Fan This.data.forEach (function (obj, i) {//each time it comes in, calculates the starting angle and end angle of the current sector//Bottom
                A fan-shaped starting angle, which is the end angle of the current sector startangle = Endangle;

                This end angle = The end angle of the previous sector + the angle of the current value Endangle = Endangle + baseangle * obj.val;
                The angle Lineangle = startangle + baseangle * OBJ.VAL/2 of the fan middle line;
                /* * To find the x and Y coordinates of the middle line according to the angle of the middle line: * x = center X + R * Math.Cos (Angletoradian (Pointangle)) * y = center Y + R * Math.sin (Angletoradian (pointangle)) * */LineX = self.x + (s ELF.R + 20) * Math.Cos (Angletoradian (Lineangle));


                Liney = Self.y + (SELF.R +) * Math.sin (Angletoradian (Lineangle));
                Draw each fan-shaped ctx.beginpath ();
                Ctx.moveto (self.x, SELF.Y);
                Ctx.arc (self.x, Self.y, SELF.R, Angletoradian (startangle), Angletoradian (Endangle));
                Ctx.closepath ();
                Ctx.fillstyle = self.colors[I];

                Ctx.fill ();
                Draw each scalloped line of Ctx.beginpath ();
                Ctx.moveto (self.x, SELF.Y);
                Ctx.lineto (LineX, Liney);
                Ctx.strokestyle = self.colors[I];

                Ctx.stroke ();
                Draw Text Ctx.textbaseline = ' center ';
                if (lineangle >= && lineangle <=) {ctx.textalign = ' right ';
                }else {ctx.textalign = ' left '; } ctx.filltext(Obj.msg, LineX, Liney);
        });

    }
    } );

Exposing the constructor to the global w.pipe = Pipe;
 } (window));
 <canvas id= "CVS" width= "$" height= "></canvas> <script src=" Pie_chart
        . js "></script> <script> var cvs = document.getElementById (' CVS ');

        var ctx = Cvs.getcontext (' 2d ');
                var pipe = new pipe (max, Max, Max, [{val:10],
            Msg: ' Mobile phone shake '}, {val:30, msg: ' Someone is knocking at the door '},
                {val:50, msg: ' Ta seems to like me '}, {val:50,
            Msg: ' It's easy to finish this thing '}, {val:50, msg: ' This exam is also possible '
        }, {val:90, msg: ' Go to bed early Tonight '},]);
    Pipe.draw (); </script> 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.