您的位置:首页 > Web前端 > HTML5

html5 canvas绘制矩形和圆形

2016-06-15 22:24 447 查看
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body onload="draw(),drawarc()">
<!--绘制的步骤:获取canvas元素->取得上下文->填充与绘制边框->设定绘图样式-->
<!--绘制其他复杂图形需要使用路径:开始创建路径->创建图形路径->关闭路径->绘制图形-->
<!--eg:绘制矩形-->
绘制矩形:<canvas id="ca"></canvas><br />
绘制圆形:<canvas id="yuan"></canvas>
</body>
</html>
<script>
//绘制矩形
function draw(){
var canvas=document.getElementById('ca'); //获取canvas元素
if (canvas==null)
return false;
var context=canvas.getContext('2d'); //取得上下文
context.fillStyle='#EEEFF';   //填充颜色
context.fillRect(0,0,400,300); //填充矩形 (矩形1)
context.fillStyle='red';
context.strokeStyle='blue'; //边框颜色
context.lineWidth=1;        //边框宽度
context.fillRect(50,50,100,100); //填充矩形(内部矩形2)
context.strokeRect(50,50,100,100); //绘制边框

}
//绘制圆形
function drawarc(){
var canvas2=document.getElementById('yuan'); //获取canvas元素
if (canvas2==null)
if(canvas2==null)
return false;
var context2=canvas2.getContext('2d');  //取得上下文
context2.fillStyle='#EEEEEF';
context2.fillRect(0,0,400,300);
var n=0;
for(var i=0;i<10;i++){
context2.beginPath();  //开始创建路径
context2.arc(i*25,i*25,i*10,0,Math.PI*2,true);  //创建圆形路径
context2.closePath();  //关闭路径
context2.fillStyle='Rgba(255,0,0,0.25)'; //设置颜色
context2.fill();  //填充图形
}
}

</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: