Draw a "Doraemon" clock with canvas

Source: Internet
Author: User

Preface: Read the JS book canvas that picture today, good happy ~ is the beloved canvas~ oh yes ~

Before I saw someone suggested that I paint blue fat, oh, how can I forget my childhood favorite blue fat, in order to express my apology to the blue fat, so today drew a moving Hello World, also is a kind of progress ~

All right, everyone, please get in the car, please do not block the passage, thank you. Let's drive.

Body:

Let's see how it works today.

Today's blue fat long so, see it still so fat, I was relieved. The world is full of positive energy, and there are people who are fatter than me, hahaha.

And then the code.

HTML section

<id= "MyCanvas"  width= "$" height= " $" > go to upgrade your browser now ~</canvas>

JS section

Window.addeventlistener ("Load",function(){        //get the canvas context        varContext = document.getElementById ("MyCanvas"). GetContext ("2d")); //determines whether the context exists, and the next code can be executed        if(context) {//Start a new sub-pathContext.beginpath (); //we're going to draw two concentric circles as the border of the clock             //draw a great circle outside.Context.arc (100,100,99,0,2*math.pi,false); //with some pretty blue padding.Context.fillstyle = "#315f9b";            Context.fill (); //draw the edge of a great circleContext.stroke (); //start a new subpath,            //This is required, otherwise the fill color will overwrite all previousContext.beginpath (); //move the start point to (194,100) the point calculated with the radius and centerContext.moveto (194,100); //draw inside the small circle (circle God?) )Context.arc (100,100,94,0,2*math.pi,false); //fill the inner circle with another nice little light blueContext.fillstyle = "#4ba2cf";            Context.fill ();            Context.stroke (); //The fat blue appears ~            //Create an Image object and set its src to the blue fat picture            varImage =NewImage (); IMAGE.SRC= "2.png"; //DrawImage the picture from the point (25,25) in a contextual way, and draw it in a rectangle with a length of 150 in the edgeContext.drawimage (image,25,25,150,150); //moving the transformation matrix            //after moving (100,100) as the new origin, i.e. (0,0)Context.translate (100,100); //to paint our time with a blue color that looks just as good.Context.fillstyle = "#02285a"; //Filltext The first argument is the string to be drawn, the second argument is X, and the third is Y            //The following x, y value is the effect after debugging, everyone according to different circumstances, and then make adjustments ohContext.filltext ("12", -5,-80); Context.filltext ("6", -4,87); Context.filltext ("3", 80,1); Context.filltext ("9", -86,1); //This function is detailed laternowtime (context); }    },false);

The dials of the above clock appear, but the clock is the most important thing is that it can show the time ah (nonsense), so the next step is to draw the pointer

Nowtime function Section

functionNowtime (context) {//creates a Date object that is used to get the local time            varMyDate =NewDate (); //get hours, minutes, seconds            varMyhour =mydate.gethours (); //convert hours to 12 o'clock            if(Myhour >= 12) {Myhour= myHour-12; }            varMymin =mydate.getminutes (); varMysec =mydate.getseconds (); //depicting hours            //used to hold the arc of the current hour on the dial.            varHourarc; //as the starting point of the circumference at 3, the radian is expressed clockwise            if(Myhour < 3) {Hourarc= 2*math.pi-(3-myhour) *MATH.PI/6; }Else{Hourarc= (myHour-3) *MATH.PI/6;            }            //when pointing to 3,6,9,12, exactly a multiple of 90°            //This is because the angle conversion to radians is biased, so the special handling            Switch(myhour) { Case0: Hourarc= Math.pi*3/2;break; Case3: Hourarc= 0; Break;  Case6: Hourarc= Math.pi/2;break; Case9: Hourarc= Math.PI; Break; }            //Call the Drawtime function to draw an hour pin on the dialDrawtime (context,hourarc,60); //depict minutes            //used to hold the current minute's radian on the dial.            varMINARC; //15 points as the starting point of the circumference, clockwise to indicate radians            if(Mymin < 15) {MINARC= 2*math.pi-(15-mymin) *math.pi/30; }Else{MINARC= (myMin-15) *math.pi/30;            }            //processing minutes, is still here because the angle conversion to radians is biased, so special handling            Switch(mymin) { Case0: MINARC= Math.pi*3/2;break; Case15: MINARC= 0; Break;  Case30: MINARC= Math.pi/2;break; Case45: MINARC= Math.PI; Break; }            //Call the Drawtime function to draw a minute pin on the dialDrawtime (context,minarc,80); //depict the second            //used to hold the arc of the current second on the dial.            varSecarc; //take 15 seconds as the starting point of the circle, clockwise to indicate radians            if(Mysec < 15) {Secarc= 2*math.pi-(15-mysec) *math.pi/30; }Else{Secarc= (mySec-15) *math.pi/30;            }            //processing seconds, still here because the angle is converted to radians is biased, so special handling            Switch(mysec) { Case0: Secarc= Math.pi*3/2;break; Case14: Secarc= 0; Break;  Case29: Secarc= Math.pi/2;break; Case44: Secarc= Math.PI; Break; }            //Call the Drawtime function to draw an hour pin on the dialDrawtime (context,secarc,80, "Red"); //set a timeout call function, every second timeout call nowtime update clockSetTimeout (function(){                //call to draw a new pointer before, of course, you should clear the original hour hand, with the Cleartime function, really useful! cleartime (context); //clear the unauthorized pointer and draw the current pointer again ~nowtime (context); },1000); }    

So, how do we specifically manipulate the context to draw pointers? I don't know, so let's get this over with today.

Just kidding, hey, take it easy (be sure to pretend to be me)

Next is the Drawtime function, which has a total of four parameters (context,thearc,thelength,color= "#000"), the context of the eye to wear is the canvas, THEARC is the angle we want to rotate the canvas, Thelength represents the length of the pointer, and color is the colour of the pointer.

functionDrawtime (context,thearc,thelength,color= "#000"){            //Saves the current canvas environment, and the Restore method works with the ability to restore the canvas contextContext.save (); //rotate the canvas, rotate incoming parameters represent the radian of rotationcontext.rotate (THEARC); //Start a new sub-path, and we'll start drawing pointers.Context.beginpath (); //move the start point to (0,0)Context.moveto (0,0); //draw a path to (thelength,0)Context.lineto (thelength,0); //draws this path with the specified color colorContext.strokestyle =color; //the width of the path is 2Context.linewidth = 2; //the path is not visible, if you want to see the path, you need to use a stroke to stroke the line, and how to stroke the line, you can use the above several properties to defineContext.stroke (); //Recovery ContextContext.restore ();}

Although it is nearing the end, but there is a very important cleartime function, if you do not have it, your clock will be occupied by a dense second hand, care for patients with fear-intensive phobia, we all have the responsibility

functionCleartime (context) {//We started a new sub-path, and then depicted a round with a nice blue color, covering the hands we had drawn before, the equivalent of wiping out a dialContext.beginpath (); Context.arc (0,0,80,0,2*math.pi,false); Context.fillstyle= "#4ba2cf";            Context.fill (); //Unfortunately, our blue fat has been accidentally hurt, so summon it again, the decision is you, Pikachu (? Hey)            varImage =NewImage (); IMAGE.SRC= "2.png"; //this coordinate is different from the coordinates of the first load, because we have modified the transformation matrix, remember? So, their coordinates should be complementary.Context.drawimage (image,-75,-75,150,150);}

Well, OK, now is really the end of it, it's almost time to eat ~ Everyone lovely program apes to remember to eat oh ~

Draw a "Doraemon" clock with canvas

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.