html5中canvas绘制矩形

来源:互联网 发布:淘宝数据抓取 编辑:程序博客网 时间:2024/05/21 09:31
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>canvas的例子(矩形)</title>

    </head>
    <body>
        <canvas id="myCanvas" width="700" height="300"></canvas>
        
        <!--
            context是一个封装了很多绘图功能的对象,canvas元素绘制图像的时候有两种方法,
                context.fill()   //填充
                context.stroke()  //绘制边框
            
            style:在进行图形绘制前,要设置好绘图的样式
                context.fillStyle  //填充的样式
                context.strokeStyle  //边框样式
                
            context.lineWidth  //图形边框宽度
            
            颜色表示:英文名,十六进制,rgb,rgba(1-255,1-255,1-255,透明度)
            
            绘制矩形:
                context.fillRect(x,y,width,height)  
                context.strokeRect(x,y,width,height)
            
            
        -->
        <script type="text/javascript">
            var canvas=document.getElementById("myCanvas");
            var context=canvas.getContext('2d');
            
            //默认填充黑色 fillStyle=black
            context.fillRect(0,0,100,100);
            
            //默认黑色边框strokeStyle
            context.strokeRect(100,100,100,100);
            
            //设置纯色
            context.fillStyle="chartreuse";
            context.strokeStyle="blue";    
            context.fillRect(0,200,100,100);
            context.strokeRect(300,100,100,100);
        
            //设置透明度,在0-1之间,值越低越透明
            context.fillStyle="rgba(255,0,0,0.1)";
            context.strokeStyle="rgba(100,124,0,0.7)";
            context.fillRect(200,200,100,100);
            context.strokeRect(500,100,100,100);
            
            context.fillStyle="cornflowerblue";
            context.fillRect(200,0,100,100);
            
            context.fillStyle="fuchsia";
            context.fillRect(400,0,100,100);
            
            context.fillStyle="darkorange";
            context.fillRect(400,200,100,100);
            
            context.fillStyle="cadetblue";
            context.fillRect(600,0,100,100);
            
            context.fillStyle="crimson";
            context.fillRect(600,200,100,100);
            
            context.strokeStyle="darkgray";
            context.strokeRect(0,0,700,300);
            
            //清除矩形区域
            context.fillStyle="aliceblue";
            context.clearRect(150,50,400,200);
        </script>
    </body>
    </html>
0 0
原创粉丝点击