1、在学习canvas之前,一定要安装一个高级浏览器,推荐最新版本的chrome.因为不是每个版本的浏览器都支持canvas.
2、canvas是用来在网页中绘图的,可以通过javascript程序在网页里面绘图。
3、canvas就是一个画布,我们使用js在上面进行绘图。
4、学习canvas需要一定的数学知识和空间想象能力。
5、如果想深入学习canvas,可以学习夜鹰教程网的canvas视频教程。
下面感受一下使用canvas绘图:
<canvas id="myCanvas"></canvas>
<script type="text/javascript">
var canvas=document.getElementById('myCanvas');
var ctx=canvas.getContext('2d');
ctx.fillStyle='#FF6600';
ctx.fillRect(0,0,80,100);
</script>
下面是一个制作loding的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{
margin: 0;
padding:0;
}
#box1{
position: absolute;
left:0px;
top:0px;
background-color: aquamarine;
}
</style>
</head>
<body>
<canvas id="box1" width="500" height="500">
</canvas>
<script type="text/javascript">
var can1=document.querySelector("#box1");//获取canvas对象 相当于画布 技术咨询QQ:1416759661 微信号:yyjcw10000
var ctx=can1.getContext("2d");//设置绘图环境 相当于画笔
function drawloding(r)//r代表loding旋转的角度
{
ctx.clearRect(0,0,can1.width,can1.height);
ctx.beginPath();
ctx.strokeStyle="white";
ctx.lineWidth=2;
ctx.arc(250,250,100,0,2*Math.PI,false);
ctx.stroke();
ctx.save();
ctx.beginPath();
ctx.lineWidth=5;
ctx.lineCap="round";
var linerstyle= ctx.createLinearGradient(100,0,0,400);
linerstyle.addColorStop(0,"red");
linerstyle.addColorStop(1,"green");
ctx.strokeStyle=linerstyle;
ctx.arc(250,250,100,0,(r/180)*Math.PI,false);
ctx.stroke();
ctx.closePath();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.lineWidth=2;
ctx.lineCap="round";
ctx.arc(250,250,95,0,(r/180)*Math.PI,false);
ctx.stroke();
ctx.closePath();
ctx.restore();
ctx.save();
ctx.beginPath();
ctx.lineWidth=2;
ctx.lineCap="round";
ctx.arc(250,250,105,0,(r/180)*Math.PI,false);
ctx.stroke();
ctx.closePath();
ctx.restore();
ctx.save();
var txtstr=parseInt(r*100/360)+"%";
ctx.beginPath();
ctx.font="lighter 18px 微软雅黑"
ctx.lineWidth=1;
ctx.strokeText(txtstr,240,260);
ctx.restore();
}
drawloding(0);
var i=0;
var timer=setInterval(function(){
i++;
if(i>360)
{
clearInterval(timer);
}
drawloding(i);
},30)
//
</script>
</body>
</html>
除此之外,还能使用canvas绘制出更多的其他图形:
无需用第三方的库,就能自己绘制出来以上的图形,如果再配合上js定时器,还可以实现动画效果。