学习笔记:

canvas 拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。canvas 元素本身是没有绘图能力的,可以看成一个画图的容器。所有的绘制工作必须在 JavaScript 内部完成:getContext("2d") 对象是内建的 HTML5 对象,拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法.

1.canvas画图流程

var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
cxt.fillStyle="#FF0000";
cxt.beginPath();
cxt.arc(70,18,15,0,Math.PI*2,true);
cxt.closePath();
cxt.fill();

2.canvas圆圈函数的具体解释

【画圆,Math.PI 函数的应用。cxt.arc(100,100,30,0,Math.PI*2,true); 括号内第一个和第二个参数,代表圆心坐标。第三个参数是圆的半径。第四个参数代表圆周起始位置。0 PI就是起始位置。沿顺时针路线,分别是0.5 PI(正下方),1 PI和1.5 PI(正上方),为画饼图提供了扇形范围的依据。 第五个参数是弧长Math.PI*2就是整个圆,Math.PI是半圆。第六个参数是一个布尔值,true是逆时针false是顺时针。】

语法:arc(定义一个中心点,半径,起始角度,结束角度,和绘图方向:顺时针或逆时针)


关于角度问题:水平靠右是0,0.5PI是向下90度(正下方),-0.5PI是向上90度(正上方)。圆的成形并不是以弧长为计算,而是以起始的角度和终止角度之间的连线为计算。


3.Math.round()

round()方法你可以这样理解:就是括号内的数+0.5之后,向下取值,比如:round(3.4)就是3.4+0.5=3.9,向下取值是3,所以round(3.4)=3; 那么round(-10.5)就是-10.5+0.5=-10,向下取值就是-10,所以round(-10.5)=-10


4.stroke()函数

ctx.stroke();绘制函数并显示出来


5.

  • JavaScript Math.ceil() 函数 -- 返回大于等于数字参数的最小整数(取整函数),对数字进行上舍入

  • JavaScript Math.floor() 函数 -- 返回小于等于数字参数的最大整数(取整函数),对数字进行上舍入





源代码如下:

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>20130829-2</title>

<style type="text/css">


body{

background:#333;

}


#canvas{

display:block;

width:300px;

margin:100px auto;

}


</style>


<script type="text/javascript">


window.onload=function(){

//canvas init

var canvas=document.getElementById("canvas");

var ctx=canvas.getContext("2d");

var W=canvas.width;

var H=canvas.height;

//variables

var degrees=0;

var new_degrees=0;

var diff=0;

var color="lightgreen";

var bgcolor="#222";

var text;

var animation_loop,redraw_loop;

function init(){

//clean the canvas everytime a chart is drawn

ctx.clearRect(0,0,W,H);

//background 360 degree arc

ctx.beginPath();

ctx.strokeStyle=bgcolor;

ctx.lineWidth=30;

ctx.arc(W/2,H/2,100,0,Math.PI*2,false);

ctx.stroke();

//Math.PI=180du

var radians=degrees*Math.PI/180;

ctx.beginPath();

ctx.strokeStyle=color;

ctx.lineWidth=30;

ctx.arc(W/2,H/2,100,0-90*Math.PI/180,radians-Math.PI/180,false);//整个圆是2PI

ctx.stroke();

//let us add text

ctx.fillStyle=color;

ctx.font="50px bebas";

text=Math.floor(degrees/360*100)+"%";

text_width=ctx.measureText(text).width;

ctx.fillText(text,W/2-text_width/2,H/2+15);

}

function draw()

{

if(typeof animation_loop!=undefined)

  clearInterval(animation_loop);

new_degrees=Math.round(Math.random()*360);

var diff=new_degrees-degrees;

animation_loop=setInterval(animate_to,1000/diff);

}

//animation for fun

function animate_to()

{

if(degrees<new_degrees)

   degrees++;

else

degrees--;

   if(degrees==new_degrees)

  clearInterval(animation_loop);

init();

}

draw();

redraw_loop=setInterval(draw,2000);

}


</script>





</head>


<body>


<canvas id="canvas" width="300" height="300">

</body>

</html>