[html5] 学习笔记-Canvas 绘制渐变图形与绘制变形图形
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[html5] 学习笔记-Canvas 绘制渐变图形与绘制变形图形相关的知识,希望对你有一定的参考价值。
在 html5 中,使用 Canvas API 绘制图形的知识,可以对绘制图形进行处理,包含使用 Canvas API 绘制渐变图形,使用 Canvas API 的坐标轴变换处理功能绘制变形图形。其中,左上方的点,为坐标轴原点(0,0)。
1、绘制渐变图形
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 <script> 6 function draw(id){ 7 var canvas = document.getElementById(id); 8 var context = canvas.getContext("2d"); 9 var g1 = context.createLinearGradient(0,0,0,300); 10 g1.addColorStop(0,"rgb(255,255,0)"); 11 g1.addColorStop(1,"rgb(0,255,255)"); 12 context.fillStyle = g1; 13 context.fillRect(0,0,500,500); 14 15 var g2 = context.createLinearGradient(0,0,300,0); 16 g2.addColorStop(0,"rgba(0,0,255,0.5)"); 17 g2.addColorStop(1,"rgba(255,0,0,0.5)"); 18 for(var i=0;i<10;i++){ 19 context.beginPath(); 20 context.fillStyle = g2; 21 context.arc(i*25,i*25,i*10,0,Math.PI*2,true); 22 context.closePath(); 23 context.fill(); 24 } 25 } 26 </script> 27 </head> 28 <body onload="draw(‘canvas‘)"> 29 <!--LinearGradient 30 context.createLinearGradient(xstart,ystart,xend,yend) 31 addColorStop(offset,color) 32 addColorStop(offset,color) 33 --> 34 <canvas id="canvas" width="500" height="500"></canvas> 35 </body> 36 </html>
2、绘制径向渐变
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 <script> 6 function draw(id){ 7 var canvas = document.getElementById(id); 8 if(canvas==null){ 9 return false; 10 } 11 var context = canvas.getContext("2d"); 12 var g1 = context.createRadialGradient(400,0,0,400,0,400); 13 <!--6个参数:起始点的坐标,半径,结束点的坐标,半径--> 14 g1.addColorStop(0.1,"rgb(255,255,0)"); 15 g1.addColorStop(0.3,"rgb(255,0,255)"); 16 g1.addColorStop(1,"rgb(0,255,255)"); 17 context.fillStyle = g1; 18 context.fillRect(0,0,500,500); 19 } 20 </script> 21 </head> 22 <body onload="draw(‘canvas‘)"> 23 <canvas id="canvas" width="500" height="500"></canvas> 24 </body> 25 </html>
3、绘制变形图形
变形方式:平移、缩放、旋转
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 <script> 6 function draw(id){ 7 var canvas = document.getElementById(id); 8 if(canvas==null){ 9 return false; 10 } 11 var context = canvas.getContext("2d"); 12 context.fillStyle = "#eeeeef"; 13 context.fillRect(0,0,500,500); 14 context.translate(200,50); 15 16 context.fillStyle = "rgba(255,0,0,0.25)"; 17 for(var i=0;i<50;i++){ 18 context.translate(25,25); 19 context.scale(0.95,0.95); 20 context.rotate(Math.PI/10); 21 context.fillRect(0,0,100,50); 22 } 23 } 24 </script> 25 </head> 26 <body onload="draw(‘canvas‘)"> 27 <!--平移:translate(x,y) 缩放:scale(x,y) 旋转:rotate(deg)--> 28 <canvas id="canvas" width="500" height="500"></canvas> 29 </body> 30 </html>
以上是关于[html5] 学习笔记-Canvas 绘制渐变图形与绘制变形图形的主要内容,如果未能解决你的问题,请参考以下文章
HTML5 Canvas 学习笔记(canvas绘制线条矩形多边形圆形圆环组合图形文字自定义图像)