绘制矩形
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>canvas绘制矩形</title> <script type="text/javascript" src="canvas.js"></script> <style type="text/css">//让矩形显示置顶 body{ margin: 0; padding: 0; } </style> </head> <body onload="draw('canvas');"> <canvas id = "canvas" width="500" height="350"></canvas> </body> </html>
//canvas.js
function draw(id){ var canvas = document.getElementById(id); var context = canvas.getContext('2d'); context.fillStyle = "#000"; context.strokeStyle = "#f60"; context.lineWidth = 5; context.fillRect(0,0,500,350); context.strokeRect(50,50,180,120); }
绘制一个矩形:
1。获取canvas元素 getElementById()
2。取得上下文 getContext()
3。填充与绘制边框 fill() stroke()
4。设置绘制样式 fillStyle stokeStyle 属性
5。指定画笔宽度 getcontext().linewidth
6。设置颜色值 通过第4步的属性来设置
7。绘制矩形 context.fillRect(x,y,width,height)
context.strokeRect(x,y,width,height)
绘制圆形:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>canvas绘制圆形</title> <script type="text/javascript" src="canvas.js"></script> <style type="text/css"> body{ margin: 0; padding: 0; } </style> </head> <body onload="draw('canvas');"> <canvas id = "canvas" width="500" height="500"></canvas> </body> </html>
function draw(id){ var canvas = document.getElementById(id); var context = canvas.getContext('2d'); context.fillStyle = "#f1f2f3"; context.fillRect(0,0,500,500);//背景的绘制 for(var i = 0;i<10;i++){ context.beginPath(); context.arc(25*i,25*i,10*i,0,Math.PI*2,true); context.closePath(); context.fillStyle = "rgba(255,0,0,0.25)"; context.fill(); } }
效果图;
绘制一个圆形:
1。创建开始路径,context.beginPath()
2.创建图形路径,context.arc(x,y,radius,starAngle,endAngle,anticlockwise);
var radius = degress*Math.PI/180, Math.PI=180度
anticlockwise 是否顺时针
3.创建完成关闭路径,context.clasePath()
4。设置绘制样式然后调用绘制方法进行绘制,context.filllStyle = 'rgba(255,0,0,0.25)';context.fill();
绘制文字:
function draw(id){ var canvas = document.getElementById(id); var context = canvas.getContext('2d'); context.fillStyle = "#a0f"; context.fillRect(0,0,800,300);//背景的绘制 context.fillStyle = "#fff";//文字的颜色 context.strokeStyle = "#fff"; context.fillText("小柠檬呢",50,50); context.strokeText("小小的柠檬",50,100);
绘制动画
var i; function draw(id){ var canvas = document.getElementById(id); context = canvas.getContext('2d'); setInterval(painting,100);//设置动画的间隔时间。第一个参数表示执行动画的函数,第二个函数 间隔时间 //通过不断地变化xy坐标来实现动画效果。clearRect(),将画布整体或者局部擦除。 i=0; } function painting(){ context.fillStyle = "#f00"; context.fillRect(i,0,10,10); i=i+20; }