动画原理——图形填充
书籍名称:HTML5-Animation-with-JavaScript
书籍源码:https://github.com/lamberta/html5-animation
1.渐变填充
渐变填充有线性渐变,和径向渐变两种。因为是用法,我们直接在代码中分析会更直观
一.
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Gradient Fill 1</title> <link rel="stylesheet" href="../include/style.css"> </head> <body> <header> Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a> </header> <canvas id="canvas" width="400" height="400"></canvas> <script> window.onload = function () { var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), pt1 = {x: 0, y: 0}, //gradient start point pt2 = {x: 100, y: 100}, //gradient end point //创建渐变,前pt为开始坐标,p2为结束坐标 gradient = context.createLinearGradient(pt1.x, pt1.y, pt2.x, pt2.y); //开始颜色为白,结束颜色为红 gradient.addColorStop(0, "#ffffff"); gradient.addColorStop(1, "#ff0000"); //填充 context.fillStyle = gradient; context.fillRect(0, 0, 100, 100); }; </script> </body> </html>
二.多种颜色
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Gradient Fill 2</title> <link rel="stylesheet" href="../include/style.css"> </head> <body> <header> Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a> </header> <canvas id="canvas" width="400" height="400"></canvas> <script> window.onload = function () { var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), pt1 = {x: 100, y: 100}, //gradient start point pt2 = {x: 200, y: 200}, //gradient end point gradient = context.createLinearGradient(pt1.x, pt1.y, pt2.x, pt2.y); //white to blue to red gradient.addColorStop(0, "#ffffff"); gradient.addColorStop(0.5, "#0000ff"); gradient.addColorStop(1, "#ff0000"); context.fillStyle = gradient; context.fillRect(100, 100, 100, 100); }; </script> </body> </html>
三.透明
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Gradient Fill Radial</title> <link rel="stylesheet" href="../include/style.css"> </head> <body> <header> Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a> </header> <canvas id="canvas" width="400" height="400"></canvas> <script> window.onload = function () { var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), c1 = {x: 150, y: 150, radius: 0}, //gradient start circle c2 = {x: 150, y: 150, radius: 50}, //gradient end circle gradient = context.createRadialGradient(c1.x, c1.y, c1.radius, c2.x, c2.y, c2.radius); //all black alpha blend gradient.addColorStop(0, "#000000"); gradient.addColorStop(1, "rgba(0, 0, 0, 0)"); //alpha required context.fillStyle = gradient; context.fillRect(100, 100, 100, 100); }; </script> </body> </html>