<canvas></canvas>是html5中新增的标签,用于绘制图形,实际上,这个标签和其他的标签一样,其特殊之处在于该标签可以获取一个canvasrenderingcontext2d对象,我们可以通过javascript脚本来控制该对象进行绘图。
<canvas></canvas>只是一个绘制图形的容器,除了id、class、style等属性外,还有height和width属性。在<canvas>>元素上绘图主要有三步:
1.获取<canvas>元素对应的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基本绘图之填充样式实现 的内容,更多相关内容请关注PHP中文网(www.php.cn)!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号