canvas作图

时间:2023-03-09 03:17:12
canvas作图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas width="500px" height="500px" id="canvas" style="background: yellow"></canvas>
<script>
var canvas = document.getElementById('canvas'); //通过id获取画布
var cxt = canvas.getContext('2d'); //getContext获取绘图环境
function drawClock(){ //获取时间
var now = new Date(); //定义时间
var sec = now.getSeconds(); //获取秒
var minute = now.getMinutes(); //获取分钟
var hourOne = now.getHours(); //获取小时
var hourTwo = hourOne + minute/60; //小时必须获取浮点类型,产生偏移(小时+分钟比)
var hour = hourTwo >12?hourTwo-12:hourTwo; //将24小时转换为12小时
cxt.beginPath(); //画笔开始
cxt.lineWidth = 5; //设置画笔的线宽
cxt.strokeStyle = ['#000']; //设置画笔的颜色
var my_gradient=cxt.createRadialGradient(250,250,225,250,250,250);
my_gradient.addColorStop(0,"#ccc");
my_gradient.addColorStop(1,"#FEC627");
cxt.fillStyle=my_gradient;
cxt.arc(250,250,250,0,360,false);//绘制圆形,坐标250,250 半径200,整圆(0-360度),false表示顺时针
cxt.fill();
cxt.stroke(); //绘图
cxt.closePath(); //结束画布
for(var i=0; i<12; i++){
cxt.save(); //保存当前环境的状态
cxt.lineWidth=7;
cxt.strokeStyle="#000"; //设置异次元空间原点
cxt.translate(250,250); //设置旋转角度
cxt.rotate(i*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-170); //画线, 从坐标0,-170开始
cxt.lineTo(0,-190); //到坐标0,-190结束
cxt.stroke();
cxt.closePath();
cxt.restore();
} //分针刻度
for(var i=0; i<60;i++){
cxt.save();
cxt.lineWidth=5;
cxt.strokeStyle="#000";
cxt.translate(250,250);
cxt.rotate(i*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-180);
cxt.lineTo(0,-190);
cxt.stroke();
cxt.closePath();
cxt.restore();
} //时针
cxt.save(); //时针样式
cxt.lineWidth = 7;
cxt.strokeStyle="#000";
cxt.translate(250,250);
cxt.rotate(/*hour**/30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-140);
cxt.lineTo(0,10);
cxt.stroke();
cxt.closePath();
cxt.restore(); //分针
cxt.save(); //分针样式
cxt.lineWidth = 5;
cxt.strokeStyle="#000";
cxt.translate(250,250);
cxt.rotate(/*minute**/6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-160);
cxt.lineTo(0,15);
cxt.stroke();
cxt.closePath();
cxt.restore();// 秒针
cxt.save();
cxt.lineWidth = 3;
cxt.strokeStyle="#f00";
cxt.translate(250,250);
cxt.rotate(/*sec**/60*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-185);
cxt.lineTo(0,20);
cxt.stroke();
cxt.closePath(); //画出时针,分针,秒针交叉点
cxt.beginPath();
cxt.strokeStyle="#f00";
cxt.arc(0,0,5,0,360,false);
cxt.fillStyle="#fff"; //填充颜色
cxt.fill(); //填充
cxt.stroke();
cxt.closePath(); //秒针装饰
cxt.beginPath();
cxt.strokeStyle="#f" + "0";
cxt.arc(0,-160,5,0,360,false);
cxt.fill();
cxt.stroke();
cxt.closePath();
cxt.restore();
}
setInterval(drawClock,1000); //使用setinterval();让时钟动起来
</script>
</body>
</html>