canvas是HTML5中新加入的标签。使用canvas可以创造完全独立于css的图形界面。canvas完全依靠js代码实现矢量图形界面的显示和变换。目前canvas在移动端界面中广泛使用。微信小游戏和小程序很多都是基于canvas进行创作(例如经典的最强弹一弹、经典跳一跳)这些小游戏不需要下载APP,直接在微信平台中运行即可进行游戏,受到不少用户的追捧。
下面这个是使用canvas制作的元宵节祝福(源码来源于网络),节假日期间受到很多朋友追捧。
使用canvas制作和使用CSS进行设计不完全一致。传统CSS可以设置图片的样式(排版),就是将设计组已经设计好的图形进行处理,对文字、图片等属性进行加工。使用canvas可以完全创造矢量图形(点、线段、多边形等),结合JS的setInternal等方法可以创造动画等效果。使用canvas操作的门槛相对高一些。
目前市场上大部分使用canvas的2d效果,3d效果使用不常见(我正在学习中),那就以2d效果为例进行分析:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>canvas</title> <style> canvas { border: 1px solid red; } </style> </head> <body> <!-- 预设代码:canvas的宽度和高度必须放在行内样式中,style中无效 --> <canvas id="cvs" width="500px" height="300px"></canvas> <script> var cvs = document.getElementById('cvs'); var ctx = cvs.getContext('2d'); //这两句代码是2d效果通用代码:获取canvas对象并绑定2d效果 ctx.moveTo(10,10); ctx.lineTo(20,10); ctx.lineTo(20,20); ctx.lineTo(10,20); //moveTo不绘制路径,lineTo绘制路径 ctx.strokeStyle = 'blue'; ctx.lineWidth = 6; // 线宽和颜色必须在绘制之前设置 ctx.stroke(); // 2.closePath()关闭路径,最后一条边省去路径自动关闭 ctx.moveTo(100,10); ctx.lineTo(160,10); ctx.lineTo(60,60); ctx.closePath(); ctx.strokeStyle = 'yellow'; ctx.lineWidth = 6; ctx.stroke(); // 设置颜色和线宽度必须在绘制之前 </script> <script> // 绘制矩形封装函数 var cvs = document.getElementById('cvs'); var ctx = cvs.getContext('2d'); function juxing(startX,startY,width,height,lineWidth,strokeStyle){ ctx.moveTo(startX,startY); ctx.lineTo(startX + width,startY); ctx.lineTo(startX+width,startY+height); ctx.lineTo(startX,startY+height); ctx.closePath(); ctx.lineWidth = lineWidth; ctx.strokeStyle = strokeStyle; ctx.stroke(); } // 为了防止重绘之前的路径,绘制新路径需要将之前的路径清除掉 ctx.beginPath(); juxing(100,100,10,20,3,"skyblue"); </script> <script> // 矩形对象封装 // 构造函数 function JuXing(ctx,startX,startY,width,height,lineWidth,strokeStyle){ this.ctx = ctx; this.startX = startX; this.startY = startY; this.width = width; this.height = height; this.lineWidth = lineWidth; this.strokeStyle = strokeStyle; } // 给原型添加一个绘制方法 JuXing.prototype.draw = function(){ this.ctx.moveTo(startX,startY); this.ctx.lineTo(startX + width,startY); this.ctx.lineTo(startX+width,startY+height); this.ctx.lineTo(startX,startY+height); this.ctx.closePath(); this.ctx.lineWidth = lineWidth; this.ctx.strokeStyle = strokeStyle; this.ctx.stroke(); } ctx.beginPath(); var juxing = new JuXing(ctx,10,10,100,100,2,"pink"); juxing.draw(); </script> <!-- 先填充后描边。描边有一个宽度,如果先描边后填充,描边的宽度会减小。所以先填充后描边 ctx.fill(); ctx.stroke(); 线帽设置: ctx.lineCap = 'round' 'square' 交点设置: ctx.lineJoin = 'miter' 'round' 'bevel'--> <script> 绘制三种矩形:矩形路径,描边矩形,填充矩形。 // 矩形路径 ctx.rect(10,10,10,10); ctx.stroke(); // 描边矩形 ctx.strokeRect(10,10,10,10); // 填充矩形 ctx.fillRect(10,10,10,10); // 清除矩形区域 ctx.clearRect(10,10,10,10); </script> <!-- 画布动画效果:设置间隔函数,不断清除旧图形,绘制新图形 --> </body> </html>