HTML5-canvas绘图
HTML5-canvas绘图
HTML5引入了<canvas>标签用于绘图,默认是一个300*150的inline-block。使用width/height属性指定尺寸,但不能使用CSS样式指定宽和高!
<canvas width="600" height="500" id="c">
您的浏览器不支持Canvas标签!
</canvas>
往“画布”上绘图需要使用其对应的“画笔”对象:
var ctx = c.getContext('2d'); //绘图上下文——“画笔”
接下来所有的绘图任务都由画笔实现。
Content:内容
Context:上下文
绘图上下文对象的常用属性——console.log(ctx):
fillStyle:'#000',填充样式
strokeStyle:'#000',描边/轮廓样式
lineWidth:1,描边/轮廓的宽度
font:'10px sans-serif',绘制文本所用的字号/字体
textBaseline:'alphabetic',文本对齐的基线
showdowOffsetX:0,阴影水平偏移量
showdowOffsetY:0,阴影竖直偏移量
showdowColor:'rgba(0,0,0,0)',阴影颜色
showdowBlur:0,阴影模糊半径

使用Canvas绘制矩形
提示:矩形的定位点在自己左上角
ctx.fillStyle = '#000' 填充颜色
ctx.strokeStyle = '#000' 描边颜色
ctx.fillRect(x,y,w,h) 填充一个矩形
ctx.strokeRect(x,y,w,h) 描边一个矩形
ctx.clearRect(x,y,w,h) 清除一个矩形范围内的所有内容
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 body { 8 text-align: center; 9 } 10 canvas { 11 background: #f0f0f0; 12 } 13 </style> 14 </head> 15 <body> 16 <h3>Canvas绘图</h3> 17 <canvas id="c8" width="600" height="400"> 18 您的浏览器不支持Canvas标签! 19 </canvas> 20 <script> 21 //获得画布对应的画笔 22 var ctx = c8.getContext('2d'); 23 24 //左上角填充矩形 25 ctx.fillRect(0,0,100,80); 26 27 //右上角描边矩形 28 ctx.lineWidth=10; 29 ctx.strokeRect(600-100,0,100,80); 30 31 //左下角填充矩形 32 ctx.fillStyle = '#f00'; 33 ctx.fillRect(0,400-80,100,80); 34 35 //右下角描边矩形 36 ctx.strokeStyle = '#0ff'; 37 ctx.strokeRect(600-100,400-80,100,80); 38 39 //正中央填充+描边一个矩形 40 ctx.fillRect(300-100/2,200-80/2, 100,80) 41 ctx.strokeRect(300-100/2,200-80/2, 100,80) 42 43 44 45 </script> 46 </body> 47 </html>
效果图如下:

使用Canvas绘制文本
提示:文字的定位点默认在文本基线的起点(左侧)
ctx.textBaseline = 'alphabetic' 文本基线,可取为top/bottom/middle/alphabetic
ctx.fillText(txt, x, y) 填充文本
ctx.strokeText(txt, x, y) 描边文本
ctx.measureText(txt).width 测量,根据当前指定的字号和字体计算指定文本的宽度
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 body { 8 text-align: center; 9 } 10 canvas { 11 background: #f0f0f0; 12 } 13 </style> 14 </head> 15 <body> 16 <h3>绘制文本</h3> 17 <canvas id="c8" width="600" height="400"> 18 您的浏览器不支持Canvas标签! 19 </canvas> 20 <script> 21 //获得画布对应的画笔 22 var ctx = c8.getContext('2d'); 23 24 //文本基线设为第一线 25 ctx.textBaseline = 'top'; 26 ctx.font = '20px SimHei'; 27 28 29 var txt = '时间脱臼的博客-canvas绘制文本'; 30 ctx.fillText(txt, 0, 0); 31 </script> 32 </body> 33 </html>
效果图如下:

为图形文字添加阴影
ctx.shadowColor = '#666'; //阴影颜色
ctx.shadowOffsetX = 8; //阴影偏移量
ctx.shadowOffsetY = 8;
ctx.shadowBlur = 10; //阴影模糊半径
在绘图时使用渐变色
//创建渐变对象
var g = ctx.createLinearGradient(50,100, 550,100);
g.addColorStop(0, '#f00'); //添加颜色点
g.addColorStop(1, '#0f0'); //添加颜色点
//使用渐变对象
ctx.fillStyle = g;
ctx.strokeStyle = g;

浙公网安备 33010602011771号