标签导航:

是html5中新增的标签,用于绘制图形,实际上,这个标签和其他的标签一样,其特殊之处在于该标签可以获取一个canvasrenderingcontext2d对象,我们可以通过javascript脚本来控制该对象进行绘图。
只是一个绘制图形的容器,除了id、class、style等属性外,还有height和width属性。在>元素上绘图主要有三步:
1.获取元素对应的dom对象,这是一个canvas对象;
2.调用canvas对象的getcontext()方法,得到一个canvasrenderingcontext2d对象;
3.调用canvasrenderingcontext2d对象进行绘图。
填充样式
前面用到的fillstyle和strokestyle除了设置颜色外,还能设置其他填充样式,这里以fillstyle为例:
•线性渐变
使用步骤
(1)var grd = context.createlineargradient( xstart , ystart, xend , yend )创建一个线性渐变,设置起始坐标和终点坐标;
(2)grd.addcolorstop( stop , color )为线性渐变添加颜色,stop为0~1的值;
(3)context.fillstyle=grd将赋值给context。
•径向渐变
该方法与线性渐变使用方法类似,只是第一步接收的参数不一样
var grd = context.createradialgradient(x0 , y0, r0 , x1 , y1 , r1 );接收起始圆心的坐标和圆半径以及终点圆心的坐标和圆的半径。
•位图填充
createpattern( img , repeat-style )使用图片填充,repeat-style可以取repeat、repeat-x、repeat-y、no-repeat。

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

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

      

        //线性渐变   

        var grd = context.createLinearGradient( 10 , 10, 100 , 350 );   

        grd.addColorStop(0,"#1EF9F7");   

        grd.addColorStop(0.25,"#FC0F31");   

        grd.addColorStop(0.5,"#ECF811");   

        grd.addColorStop(0.75,"#2F0AF1");   

        grd.addColorStop(1,"#160303");   

        context.fillStyle = grd;   

        context.fillRect(10,10,100,350);   

      

        //径向渐变   

        var grd = context.createRadialGradient(325 , 200, 0 , 325 , 200 , 200 );   

        grd.addColorStop(0,"#1EF9F7");   

        grd.addColorStop(0.25,"#FC0F31");   

        grd.addColorStop(0.5,"#ECF811");   

        grd.addColorStop(0.75,"#2F0AF1");   

        grd.addColorStop(1,"#160303");   

        context.fillStyle = grd;   

        context.fillRect(150,10,350,350);   

      

        //位图填充   

        var bgimg = new Image();   

        bgimg.src = "background.jpg";   

        bgimg.onload=function(){   

            var pattern = context.createPattern(bgimg, "repeat");   

            context.fillStyle = pattern;   

            context.strokeStyle="#F20B0B";   

            context.fillRect(600, 100, 200,200);   

            context.strokeRect(600, 100, 200,200);   

        };

效果如下:

HTML5 canvas基本绘图之填充样式实现