canvas 从零开始升华
话不多少 直接上代码 注释很 详细
创建canvas并画一条线
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <!-- 注意:canvas的高宽最好通过属性设置 通过css样式设置会导致画布拉升导致画的内容失真 --> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> //获取画布 var cans = document.getElementById('cans'); //获取画布上下文 var pen = cans.getContext('2d'); //开始一条路径 pen.beginPath(); //确定起点 pen.moveTo(100,100); //确定结束点 pen.lineTo(400,100); //设置颜色 pen.strokeStyle='red'; //设置宽度 pen.lineWidth = 2 ; //着色 pen.stroke(); //结束路径 pen.closePath() </script> </body> </html>
通过简单的封装简化划线
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> //获取画布 var cans = document.getElementById('cans'); //获取画布上下文 var pen = cans.getContext('2d'); runcanvs(100,100,400,100,'red',2); runcanvs(400,100,400,400,'green',2); runcanvs(400,400,100,400,'yellow',2); runcanvs(100,400,100,100,'blue',2); //为其封装函数 方便调用 function runcanvs(x1,y1,x2,y2,color,width ){ pen.beginPath(); pen.moveTo(x1,y1); pen.lineTo(x2,y2); pen.strokeStyle=color; pen.lineWidth = width; pen.stroke(); pen.closePath() } //直线多用 // pen.beginPath(); // pen.moveTo(100,100); // pen.lineTo(400,100); // //lineTo可以多次调用 // pen.lineTo(400,400); // pen.lineTo(100,400); // pen.strokeStyle='red'; // pen.lineWidth = 2 ; // pen.stroke(); // pen.closePath() </script> </body> </html>
清除画布上的类容(相当于橡皮檫)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); pen.fillStyle='green'; pen.fillRect(100,100,300,300); //清除画布 // pen.clearRect(x,y,width,height) x,y起始坐标 width,height 清除的高宽 pen.clearRect(120,120,100,100) </script> </body> </html>
画虚线
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); function runcanvs(x1,y1,x2,y2,color,width ){ pen.beginPath(); pen.moveTo(x1,y1); pen.lineTo(x2,y2); pen.strokeStyle=color; pen.lineWidth = width; pen.stroke(); pen.closePath() } //画虚线 for (var i = 0 ;i < 20;i++){ runcanvs(100+10*i,100,105+10*i,100,'red',2); } //通过改变y轴的参数可以纵向虚线 for (var i = 0 ;i < 20;i++){ runcanvs(100,100+10*i,100,105+10*i,'red',2); } //通过同时改变x,y轴的参数 画斜向 的虚线 for (var i = 0 ;i < 20;i++){ runcanvs(100+10*i,100+10*i,105+10*i,105+10*i,'red',2); } </script> </body> </html>
画矩形
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); //画3种类型的矩形 //第一种 可以描边 可以填充 // pen.rect(x,y,width,height) 绘制矩形 x,y起始的坐标 width,height宽高 pen.rect(100,100,100,100); //需要同时描边和填充的时候 需要先填充在描边 (先描边后填充的话会导致描的边被填充的颜色覆盖) //填充 //设置颜色 pen.fillStyle='red'; //填充颜色 pen.fill(); //描边 //设置描边的颜色 pen.strokeStyle='bule'; //设置描边的宽度 pen.lineWidth=5 //应用描边 pen.stroke(); //第二种 可以填充 不能描边 // fillRect(x,y,widht,height) 实心的矩形 属性同rect //设置填充的颜色 不然会依然使用上面的颜色 pen.fillStyle='gold'; //调用画矩形的函数画出矩形 pen.fillRect(300,100,100,100); //第三种 可以描边 不能填充 // strokeRect(x,y,widht,height) 属性同上 //设置颜色和宽度 pen.strokeStyle='purple'; pen.lineWidth=6; //应用样式生成 矩形 pen.strokeRect(100,300,100,100); </script> </body> </html>
通过举行生成一个统计图
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <button id="btn1">stop</button> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); //定义坐标轴 //定义数据条形图 // pen.fillStyle='red'; // pen.fillRect(200,200,20,200); //随机生成数据条形图 pen.beginPath(); pen.moveTo(100,100); pen.lineTo(100,400); pen.lineTo(400,400); pen.stroke(); pen.closePath(); for (var i=0 ;i<7;i++) { var heig= parseInt(Math.random()*280)+10; var str = Math.random().toString(16).slice(-6) console.log(str); pen.fillStyle='#'+str; pen.fillRect(120+40*i,400-heig,20,heig); } </script> </body> </html>
画一格圆
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); //画圆 //pen.arc(x,y,radius,startAngle,endAngle,counterclockwise) //x,y 圆心的坐标 //radius 半径的长度 //startAngle 开始的度数 x轴 0-----→∞ 的方向为0度 //endAngle 结束的毒素 y轴 0↓-∞ 的方向为 正的1/2π 度 pen.arc(200,200,100,0,Math.PI,false); //描边宽度 pen.lineWidth=10; //填充颜色 pen.fillStyle='red'; pen.fill(); //应用描边 pen.stroke(); //应用升级 pen.beginPath(); pen.arc(100,100,50,0,Math.PI,true) pen.stroke(); pen.beginPath(); pen.arc(200,100,50,0,Math.PI,false); pen.stroke(); //同心圆 pen.beginPath(); pen.arc(200,200,50,Math.PI*2,false); pen.stroke(); pen.beginPath(); pen.arc(200,200,150,Math.PI*2,false); pen.stroke(); pen.beginPath(); pen.arc(200,200,180,Math.PI*2,false); pen.stroke(); </script> </body> </html>
动态画圆
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); //动态画圆 //将圆度分为360度 var deg = Math.PI*2/360; //设置变量用于 逐渐增大 度数 var counter = 0; //设置定时器 var timer = setInterval(function(){ pen.beginPath(); counter++; pen.arc(200,200,100,0,counter*deg,false); pen.lineWidth=4; pen.strokeStyle='red'; pen.stroke(); if(counter==360){ clearInterval(timer); } },50) </script> </body> </html>
通过碰撞检测让一个圆在固定范围类来回的弹
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); //collision detection碰撞检测 var w = 500; var h = 500; var x = 50; var y = 50; var r = 25; var xspeed = 3; var yspeed = 1; var timer = setInterval(function(){ pen.clearRect(0,0,w,h); pen.beginPath(); if(x-r<0||x+r>w){ xspeed = -xspeed; } if(y-r<0||y+r>h){ yspeed = -yspeed; } x = x+xspeed; y = y+yspeed; drawcircle(x,y,r); },10) function drawcircle(x,y,r){ pen.arc(x,y,r,0,Math.PI*2); pen.fillStyle='red'; pen.fill(); } </script> </body> </html>
通过碰撞检测和封装对象生成多个圆在固定范围类来回的弹
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); //collision detection碰撞检测 var w = 500; var h = 500; function r(num){ return Math.random()*num; } //定义生成的小球的属性 function Ball(){ // this.x = r(500); // this.y = r(500); // this.x = r(60)+60; // this.y = r(60)+60; this.x = 60; this.y = 60; this.r = r(30)+10; this.color = '#'+Math.random().toString(16).slice(-6); this.xspeed = r(2)+6; this.yspeed = r(3)+7; } //定义小球显示的方法 Ball.prototype.show = function(){ pen.beginPath(); pen.arc(this.x,this.y,this.r,0,Math.PI*2); pen.fillStyle = this.color; pen.fill(); this.run(); } //定义小球的运动方法 (collision detection) Ball.prototype.run = function(){ if(this.x-this.r<=0||this.x+this.r>=w){ this.xspeed = -this.xspeed; } if(this.y-this.r<=0||this.y+this.r>=h){ this.yspeed = -this.yspeed; } this.x = this.x+this.xspeed; this.y = this.y+this.yspeed; } // new Ball().show() // new Ball().show() // new Ball().show() //用循环生成多个小球 var ballArr = []; for (let i= 0; i < 200; i++) { var ball = new Ball(); ballArr.push(ball); ball.show(); } setInterval(() => { //清除画布 pen.clearRect(0,0,w,h); for(var i=0;i<ballArr.length;i++){ var ball = ballArr[i]; //跟新小球坐标 让其动起来 // ball.run(); //刷新 ball.show() } }, 20); </script> </body> </html>
让多个圆连线并添加文字和碰撞检测
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> /** @type {HTMLCanvasElement} */ var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); //定义高宽 var w = 500; var h =500; //定义一堆文字 var titleArr = "html html5 css javascript scss bootstrap vue vuex axios jquery dom bom nodejs http https ajxa".split(' ') //产生随机数 function r(num){ return Math.random()*num; } //创建小球类 function Ball(text){ //随机位置产生小球 this.x = r(380)+60; this.y = (380)+60; this.r = r(30)+10; this.color = '#'+Math.random().toString(16).slice(-6); this.xspeed = r(2)+2; this.yspeed = r(3)+3; //接收外部参数 this.text = text; } //生成小球 Ball.prototype.show = function(){ this.run()//更新小球坐标 drawCircle(this.x,this.y,this.r,this.color)//画小球 drawText(this.text,this.x+this.r,this.y)//画文字 } //collision detecation Ball.prototype.run = function(){ if(this.x-this.r<=0||this.x+this.r>=w){ this.xspeed = -this.xspeed; } if(this.y-this.r<=0||this.y+this.r>=h){ this.yspeed = -this.yspeed; } this.x = this.x+this.xspeed; this.y = this.y+this.yspeed; } //画直线 function darwLine(x1,y1,x2,y2,color){ pen.beginPath(); pen.moveTo(x1,y1); pen.lineTo(x2,y2); pen.strokeStyle=color||'#000'; pen.stroke(); pen.closePath(); } //画文字 function drawText(text,x,y){ pen.font = '20px 仿宋'; pen.textAlign = 'top'; pen.textBaseline = 'middle'; pen.fillText(text,x,y); } //画圆 function drawCircle(x,y,r,color){ pen.beginPath(); pen.arc(x,y,r,0,Math.PI*2); pen.fillStyle=color||"#000"; pen.fill(); } //测试是否生成了小球 // new Ball().show(); //定义一个数组来存放生成的多个小球 var ballArr = []; for (let i = 0; i < 5; i++) { //i当前小球 var ball = new Ball(titleArr[i]); ballArr.push(ball); ball.show(); //小球的连线 for (let j = 0; j< i; j++) { //取出当前小球前面的小球 var prevBall = ballArr[j]; darwLine(ball.x,ball.y,prevBall.x,prevBall.y,ball.color) } } //小球运动 setInterval(() => { //清除画布 pen.clearRect(0,0,w,h); for (let i= 0; i < ballArr.length; i++) { var ball = ballArr[i]; ball.show(); for (let j = 0; j< i; j++) { //取出当前小球前面的小球 var prevBall = ballArr[j]; darwLine(ball.x,ball.y,prevBall.x,prevBall.y,ball.color) } } },150); </script> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> *{ margin: 0;padding: 0; } </style> </head> <body> <canvas id="cans" >您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> /** @type {HTMLCanvasElement} */ var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); //定义高宽 var w = document.documentElement.clientWidth-6; var h =document.documentElement.clientHeight-6; cans.width = w; cans.height = h; //定义一堆文字 var titleArr = "html html5 css javascript scss bootstrap vue vuex axios jquery dom bom nodejs http https ajxa".split(' ') //产生随机数 function r(num){ return Math.random()*num; } //创建小球类 function Ball(text){ //随机位置产生小球 this.x = r(380)+60; this.y = (380)+60; this.r = r(30)+10; this.color = '#'+Math.random().toString(16).slice(-6); this.xspeed = r(2)+2; this.yspeed = r(3)+3; //接收外部参数 this.text = text; } //生成小球 Ball.prototype.show = function(){ this.run()//更新小球坐标 drawCircle(this.x,this.y,this.r,this.color)//画小球 drawText(this.text,this.x+this.r,this.y)//画文字 } //collision detecation Ball.prototype.run = function(){ if(this.x-this.r<=0||this.x+this.r>=w){ this.xspeed = -this.xspeed; } if(this.y-this.r<=0||this.y+this.r>=h){ this.yspeed = -this.yspeed; } this.x = this.x+this.xspeed; this.y = this.y+this.yspeed; } //画直线 function darwLine(x1,y1,x2,y2,color){ pen.beginPath(); pen.moveTo(x1,y1); pen.lineTo(x2,y2); pen.strokeStyle=color||'#000'; pen.stroke(); pen.closePath(); } //画文字 function drawText(text,x,y){ pen.font = '20px 仿宋'; pen.textAlign = 'top'; pen.textBaseline = 'middle'; pen.fillText(text,x,y); } //画圆 function drawCircle(x,y,r,color){ pen.beginPath(); pen.arc(x,y,r,0,Math.PI*2); pen.fillStyle=color||"#000"; pen.fill(); } //测试是否生成了小球 // new Ball().show(); //定义一个数组来存放生成的多个小球 var ballArr = []; for (let i = 0; i < 5; i++) { //i当前小球 var ball = new Ball(titleArr[i]); ballArr.push(ball); ball.show(); //小球的连线 // for (let j = 0; j< i; j++) { // //取出当前小球前面的小球 // var prevBall = ballArr[j]; // darwLine(ball.x,ball.y,prevBall.x,prevBall.y,ball.color) // } } //小球运动 setInterval(() => { //清除画布 pen.clearRect(0,0,w,h); for (let i= 0; i < ballArr.length; i++) { var ball = ballArr[i]; ball.show(); for (let j = 0; j< i; j++) { //取出当前小球前面的小球 var prevBall = ballArr[j]; darwLine(ball.x,ball.y,prevBall.x,prevBall.y,ball.color) } } },10); </script> </body> </html>
随着鼠标的移动生成圆并逐渐缩小消失
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> *{ margin: 0;padding: 0; } </style> </head> <body> <canvas id="cans" >您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> /** @type {HTMLCanvasElement} */ var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); //定义高宽 var w = document.documentElement.clientWidth-6; var h =document.documentElement.clientHeight-6; cans.width = w; cans.height = h; //产生随机数 function r(num){ return Math.random()*num; } //创建小球类 function Ball(x,y){ //随机位置产生小球 this.x = x; this.y = y; this.r = 60; this.color = '#'+Math.random().toString(16).slice(-6); } //生成小球 Ball.prototype.show = function(){ //半径逐渐减小 this.r--; drawCircle(this.x,this.y,this.r,this.color)//画小球 } function drawCircle(x,y,r,color){ pen.beginPath(); pen.arc(x,y,r,0,Math.PI*2); pen.fillStyle=color||"#000"; pen.fill(); } var ballArr =[]; window.onmousemove=function(e){ var ball = new Ball(e.x,e.y); ball.show(); ballArr.push(ball); } setInterval(() => { pen.clearRect(0,0,w,h); for (let i = 0; i < ballArr.length; i++) { var ball = ballArr[i]; if(ball.r<10){ ballArr.splice(i,1); }else{ ball.show(); } } }, 10); </script> </body> </html>
画一个字
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <button id="btn1">stop</button> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); //画文字 //fillText() 在画布上绘制填色的文字,默认颜色是黑色 //fillText(text,x,y,maxWidth) //text 规定在画布上输出的文本 //x,y 相对于画布的起始坐标 //maxWidth 可选 允许最大的文本宽度,单位为像素 //设置字体相关的样式通过font 属性 pen.font = '100px 宋体'; //设置文字颜色 pen.fillStyle = 'red'; //画文字 pen.fillText('hello',250,250) //绘制空心文字 //设置颜色 pen.strokeStyle = 'gold' pen.strokeText('你好',0,250); //设置文字颜色 pen.fillStyle = 'bule'; //画文字并设置最大宽度 pen.fillText('hello world',100,100,300) </script> </body> </html>
对画的字进行样式操作
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> /** @type {HTMLCanvasElement} */ var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); //画文字 //fillText() 在画布上绘制填色的文字,默认颜色是黑色 //fillText(text,x,y,maxWidth) //text 规定在画布上输出的文本 //x,y 相对于画布的起始坐标 //maxWidth 可选 允许最大的文本宽度,单位为像素 pen.font = '100px 仿宋'; //设置渐变 从(0,0)坐标开始渲染整个画布宽度 从0%开始? var grandient = pen.createLinearGradient(0,0,cans.width,0); //设置宽度百分比颜色渐变 grandient.addColorStop("0",'yellow'); //到50% 边黄 grandient.addColorStop("0.5",'red'); grandient.addColorStop("1",'pink'); //应用渐变色 pen.fillStyle=grandient; pen.fillText('博客园我的',0,100,500); pen.strokeStyle=grandient; pen.strokeText('点赞的都是好人',0,300,500); </script> </body> </html>
画的字的位置
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> /** @type {HTMLCanvasElement} */ var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); pen.beginPath(); pen.moveTo(250,0); pen.lineTo(250,500); pen.stroke(); pen.closePath(); pen.beginPath(); pen.moveTo(0,250); pen.lineTo(500,250); pen.stroke(); pen.closePath(); pen.font = '100px 仿宋'; //设置水平位置 // pen.textAlign='end'; // pen.textAlign='center'; // pen.textAlign='left'; // pen.textAlign='right'; //设置垂直位置 // pen.textBaseline='top'; // pen.textBaseline='middle'; pen.fillText('HTML5',250,250); </script> </body> </html>
画一张图片
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #cans{ margin: 0 auto; display: block; border: 1px solid red; } </style> </head> <body> <button id="btn1">stop</button> <canvas id="cans" width="500px" height="500px">您的浏览器版本过低请升级您的浏览器或用Chrome打开~~</canvas> <script> /** @type {HTMLCanvasElement} */ var cans = document.getElementById('cans'); var pen = cans.getContext('2d'); //3种方法 //1 3个参数 context.drawImage(图片,x,y) //2 5个参数 context.drawImage(图片,x,y,在画布上的宽,在画布上的高) //3 9 个参数 context.drawImag(图片,裁剪起始x,裁剪y,裁剪宽,裁剪高,在画布上的坐标x,坐标y,图片宽,图片高) var img = new Image(); img.src = './1 (36).jpg' //图片加载成功触发函数 img.onload = function(){ //获取图片的宽高 console.log(img.width,img.height) // pen.drawImage(img,0,0) //3个参数 // pen.drawImage(img,0,0,250,250) 5个参数 // pen.drawImage(img,0,0,100,100,0,0,100,100)//从0,0裁剪图片宽高个100,放到画布上0,0位置占宽高个100 } </script> </body> </html>
用画笔实现网页签名的功能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body > button:first-child { position: fixed; top: 200px; right: 200px; } body > button:last-child { position: fixed; top: 100px; right: 200px; } canvas { border: 1px solid red; } </style> </head> <body> <canvas id="canvas"></canvas> <button onclick="downloadIamge()">下载图片</button> <button onclick="clearCanvas()">清空画布</button> </body> <script> let can = document.getElementById("canvas"); let wh = window.innerHeight-50; let ww = window.innerWidth-10; console.log(wh, ww); can.height = wh; can.width = ww; let pen = can.getContext("2d"); let downloadIamge = function (imgsrc = "./img", name = "test") { //下载图片地址和图片名 let image = new Image(); // 解决跨域 Canvas 污染问题 image.setAttribute("crossOrigin", "anonymous"); pen.drawImage(image, 0, 0, can.width, can.height); let url = can.toDataURL("image/png"); //得到图片的base64编码数据 let a = document.createElement("a"); // 生成一个a元素 let event = new MouseEvent("click"); // 创建一个单击事件 a.download = name || "图片"; // 设置图片名称 a.href = url; // 将生成的URL设置为a.href属性 a.dispatchEvent(event); // 触发a的单击事件 // image.src = imgsrc; }; let clearCanvas = function () { pen.clearRect(0, 0, 500, 500); }; //鼠标滑动的时候划线 let checkmouseover = function (el) { // console.log(el.clientX, el.clientY); pen.lineTo(el.clientX, el.clientY); pen.stroke(); }; //取消单击时画画结束 取消监听 鼠标移动,鼠标离开事件 let checkmouseup = function (ele) { pen.stroke(); pen.closePath(); window.removeEventListener("mousemove", checkmouseover); window.removeEventListener("mouseleave", checkmouseup); }; //当鼠标 点击的时候开始监听 鼠标移动事件以及 鼠标离开事件 window.onmousedown = function (e) { pen.beginPath(); pen.moveTo(e.clientX, e.clientY); pen.strokeStyle = "pink";//控制画笔颜色 pen.lineWidth = 10; //控制划线的 粗细 window.addEventListener("mousemove", checkmouseover); window.addEventListener("mouseup", checkmouseup); }; </script> </html>