首先明白cavans基本的属性方法:
直线:<canvas id="myCanvas" width="200" height="100"style="border:1px solid #000000;"></canvas>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);ctx.stroke();
圆:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
文本:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="30px Arial";
ctx.strokeText("Hello World",10,50);
综合实例:
function toCanvas(id ,progress){
var canvas = document.getElementById(id),
ctx = canvas.getContext("2d"),
percent = progress,
circleX = canvas.width / 2,
circleY = canvas.height / 2,
radius = 100,
lineWidth = 5,
fontSize = 20;
function circle(cx, cy, r) {
ctx.beginPath();
//ctx.moveTo(cx + r, cy);
ctx.lineWidth = lineWidth;
ctx.strokeStyle = '#eee';
ctx.arc(cx, cy, r, Math.PI * 4/6, Math.PI * 1/3, false);
ctx.stroke();
}
function sector(cx, cy, r, startAngle, endAngle, anti) {
ctx.beginPath();
//ctx.moveTo(cx, cy + r); // 从圆形底部开始画
ctx.lineWidth = lineWidth;
ctx.strokeStyle = "red";
ctx.lineCap = 'round';
ctx.arc(cx, cy, r, Math.PI*4/6, (Math.PI*4/6)+endAngle/100*(Math.PI+(Math.PI*4/6)),false);
ctx.stroke();
}
function loading() {
if (process >= percent) {
clearInterval(circleLoading);
}
ctx.clearRect(0, 0, circleX * 2, circleY * 2);
ctx.font = fontSize + 'px April';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#999';
ctx.fillText(parseFloat(process).toFixed(0) + '%', circleX, circleY);
circle(circleX, circleY, radius);
sector(circleX, circleY, radius, Math.PI*2/3, process);
if (process / percent > 0.90) {
process += 0.30;
} else if (process / percent > 0.80) {
process += 0.55;
} else if (process / percent > 0.70) {
process += 0.75;
} else {
process += 1.0;
}
}
var process = 0.0;
var circleLoading = window.setInterval(function () {
loading();
}, 20);
}
toCanvas('canvas',50);
网友评论