We all have clocks on our desktops. Today, this function is implemented through the canvas canvas. The effect is as follows:
Canvas is translated as canvas in Chinese, just like a writing board. It provides us with a painting environment on which we can draw what we want to draw. One thing to note is that canvas is drawn through javaScript. If we want to draw something on canvas, we must first create a drawing environment:
//3d绘制环境还不是很稳定var ogc=oc.getContext("2d");
Then draw various patterns by calling many methods of canvas, For example:
1. Draw a rectangle
ogc.strokeRect(x,ywidth,height);
2. Draw a circle
ogc.orc(x,y,半径,0,要转的角度,是否为顺时针false);
3. Draw a straight line
ogc.moveTo(10,10);ogc.lineTo(10,50);ogc.stroke();
Draw the hour hand, minute hand, The second hand is drawn by drawing a circle, but the angle turned between them is 0.
//画小时 用画圆的方法来画,从0度到0度,中间转动的角度为0 ogc.beginPath(); ogc.lineWidth=4;//线的粗细 ogc.moveTo(x,y); ogc.arc(x,y,r*(15/20),hourvalue,hourvalue,false); ogc.closePath(); //stroke()一定要有,不然页面上就什么也没有 ogc.stroke();
Generally, there must be a beginning and an end:
ogc.beginPath(); 。。。。。。 ogc.closePath();
How to draw the scale on the dial?
Answer: Draw a smaller circle under the large dial, and then fill it with white, so that all the straight lines only show part of it.
If you want to set the thickness of the line, use ogc.lineWidth=value;
//将60个刻度蒙住 思路:在这个基础上画一个小一点的圆,然后将它填充为白色 ogc.fillStyle='white'; ogc.beginPath(); ogc.arc(x,y,r*(19/20),0,360*(Math.PI/180)); ogc.closePath(); ogc.fill();
After drawing the dial, the most important thing is How to make it move, a timer is used here, and the second hand moves one mark (6 degrees) every second, but we must first get the system time, and then get the hours, minutes, and seconds.
var date=new Date(); //得到小时 var hour=date.getHours(); //将小时转换为弧度 var hourvalue=(hour*30-90)*(Math.PI/180); //得到分钟 var minute=date.getMinutes(); var minutevalue=(minute*6-90)*(Math.PI/180); //得到秒钟 var second=date.getSeconds(); var secondvalue=(second*6-90)*(Math.PI/180);
The position where hourvalue, minutevalue, and secondvalue draw lines for hour, minute, and second hands.
The above is the detailed content of Use Canvas to implement clock rotation. For more information, please follow other related articles on the PHP Chinese website!