本文主要包含html5,canvas等相关知识,匿名希望在学习及工作中可以帮助到您
1)HTMLCanvasElement对象的成员:
height——对应于canvas元素的height属性;
width——对应于canvas元素的width属性;
getContext(<context>)——为画布返回绘图上下文;
2)绘制矩形:
fillRect(x,y,w,h)——绘制一个实心矩形;
strokeRect(x,y,w,h)——绘制一个空心矩形;
clearRect(x,y,w,h)——清除指定的矩形;
canvas{ border:medium double black; margin: 4px; } body > *{ float: left; }
<canvas id="canvas1" width="500" height="200"> 您的浏览器不支持<code>canvas</code>! </canvas>
<script> //绘制矩形 var ctx=document.getElementById("canvas1").getContext("2d"); //ctx.fillRect(10,10,50,50); var offset=10; var size=50; var count=5; for(var i=0;i<count;i++){ ctx.fillRect(i*(offset+size)+offset,offset,size,size); ctx.strokeRect(i*(offset+size)+offset,(2*offset)+size,size,size); ctx.clearRect(i*(offset+size)+offset,offset+5,size,size-10); } </script>
3)设置画布绘制状态:
lineWidth——获取或设置线条的宽度(默认值为1.0);
lineJoin——获取或设置线条与图形连接时的样式(默认值为miter);
fillStyle——获取或设置用于实心图形的样式(默认值为black);
strokeStyle——获取或设置用于线条的样式(默认值为black);
<canvas id="canvas2" width="500" height="70"> 您的浏览器不支持<code>canvas</code>! </canvas>
<script> //在执行操作前绘制设置状态 var ctx=document.getElementById("canvas2").getContext("2d"); ctx.lineWidth=2; ctx.strokeRect(10,10,50,50); ctx.lineWidth=4; ctx.strokeRect(70,10,50,50); ctx.lineWidth=6; ctx.strokeRect(130,10,50,50); ctx.lineWidth=8; ctx.strokeRect(200,10,50,50); </script>
<canvas id="canvas3" width="500" height="140"> 您的浏览器不支持<code>canvas</code>! </canvas>
<script> //设置lineJoin属性 var ctx=document.getElementById("canvas3").getContext("2d"); ctx.lineWidth=20; ctx.lineJoin="round"; ctx.strokeRect(20,20,100,100); ctx.lineJoin="bevel"; ctx.strokeRect(160,20,100,100); ctx.lineJoin="miter"; ctx.strokeRect(300,20,100,100); </script>
<canvas id="canvas4" width="500" height="140"> 您的浏览器不支持<code>canvas</code>! </canvas>
<script> //设置填充和笔触样式 var ctx=document.getElementById("canvas4").getContext("2d"); var offset=10; var size=50; var count=5; var lineWidth=3; var fillColors=["black","grey","lightgrey","red","blue"]; var strokeColors=["rgb(0,0,0)","rgb(100,100,100)","rgb(200,200,200)","rgb(255,0,0)","rgb(0,0,255)"]; for(var i=0;i<count;i++){ ctx.fillStyle=fillColors[i]; ctx.strokeStyle=strokeColors[i]; ctx.fillRect(i*(offset+size)+offset,offset,size,size); ctx.strokeRect(i*(offset+size)+offset,(2*offset)+size,size,size); } </script>
4)使用渐变
createLinearGradient(x0,y0,x1,y1)——创建线性渐变,返回CanvasGradient对象;
createRadialGradient(x0,y0,r0,x1,y1,r1)——创建径向渐变,返回CanvasGradient对象;
CanvasGradient对象的方法:
addColorStop(<position>,<color>)——给渐变的梯度线添加一种纯色;
<canvas id="canvas5" width="500" height="140"> 您的浏览器不支持<code>canvas</code>! </canvas>
<script> //使用线性渐变 var ctx=document.getElementById("canvas5").getContext("2d"); //var grad=ctx.createLinearGradient(0,0,500,140); var grad=ctx.createLinearGradient(10,10,60,60); grad.addColorStop(0,"red"); grad.addColorStop(0.5,"white"); grad.addColorStop(1,"black"); ctx.fillStyle=grad; //ctx.fillRect(0,0,500,140); ctx.fillRect(10,10,50,50); </script>
<canvas id="canvas6" width="500" height="140&quo