1 绘制五角星
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>五角星绘制</title> <style type="text/css"> #canvas{ border: 1px solid #ADACB0; display: block; margin: 20px auto; } </style> </head> <body> <canvas id="canvas" width="500" height="500"> 你的浏览器还不支持canvas </canvas> </body> <script type="text/javascript"> var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); context.fillStyle = "#F6F152"; context.strokeStyle = "#F5270B"; context.beginPath(); //设置是个顶点的坐标,根据顶点制定路径 for (var i = 0; i < 5; i++) { context.lineTo(Math.cos((18+i*72)/180*Math.PI)*200+230, -Math.sin((18+i*72)/180*Math.PI)*200+230); context.lineTo(Math.cos((54+i*72)/180*Math.PI)*80+230, -Math.sin((54+i*72)/180*Math.PI)*80+230); }//Math.PI返回圆周率 context.shadowBlur=10; context.shadowColor="blue"; context.closePath(); //设置边框样式以及填充颜色 context.lineWidth="3"; context.fill(); context.stroke(); </script> </html>
2 绘制半圆
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>半圆</title> </head> <body> <canvas id="demo" width="300" height="300" style="border:1px solid #ccc"></canvas> <script type="text/javascript"> var canvas=document.getElementById("demo"); var ctx=canvas.getContext("2d"); ctx.fillStyle="red"; ctx.strokeStyle="black"; ctx.lineWidth=5; ctx.beginPath(); ctx.arc(150,150,130,0,Math.PI,true); ctx.closePath(); ctx.fill(); ctx.stroke(); </script> </body> </html>
3 渐变文字
<!DOCTYPE html> <html> <head> <title>渐变文字</title> <meta charset="utf-8"> </head> <body> <canvas id="demo" width="800" height="600">你的浏览器不支持canvas</canvas> <script type="text/javascript"> var canvas=document.getElementById('demo'); ctx=canvas.getContext('2d'); grd=ctx.createLinearGradient(0, 0, canvas.width, 0); grd.addColorStop('0','black'); grd.addColorStop('0.3','green'); grd.addColorStop('0.6','yellow'); grd.addColorStop('1','red'); ctx.font = '80px yahei'; ctx.fillStyle= grd; ctx.fillText('我喜欢Web前端', 100, 100); </script> </body> </html>
4 图文混排
<!DOCTYPE html> <html> <head> <title>图文混排</title> <meta charset="utf-8"> </head> <body> <canvas id="demo" width="1000" height="800"></canvas> <script type="text/javascript"> var canvas=document.getElementById("demo"); var ctx=canvas.getContext("2d"); ctx.fillStyle='#99f'; ctx.fillRect(0,0,800,600); var image=new Image(); image.src="1.jpg"; image.onload=function(){ ctx.drawImage(image,20,20,300,560); } ctx.fillStyle = '#fff'; // 文字填充颜色 ctx.font = '33px 微软雅黑'; ctx.fillText('小朋友观看长颈鹿',390,100); ctx.fillStyle = '#fff'; ctx.font = '66px 微软雅黑'; ctx.fillText('大家很开心!',390,200); ctx.stroke(); </script> </body> </html>