当前位置:   article > 正文

HTML5 canvas元素绘制花朵、烟花动画和刮刮乐_html实现刮刮乐

html实现刮刮乐

HTML5 canvas元素绘制花朵、烟花动画和刮刮乐

canvas是在HTML5中新增的标签用于在网页实时生成图像,并且可以操作图像内容,可通过脚本(通常是JavaScript)动态绘制图形。权威资料可见:

Canvas 教程 - Web API 接口参考 | MDN

HTML 画布

本文包括几个例子:HTML5 canvas元素绘制花朵、HTML5 canvas粒子烟花绽放动画、HTML5 canva实现刮刮乐。

HTML5 canvas元素绘制花朵

先给出演示图如下:

源码如下:

  1. <!DOCTYPE html>
  2. <meta charset="UTF-8">
  3. <title>使用canvas元素绘制美丽的花朵</title>
  4. <head>
  5. <script >
  6. var context;
  7. var A,n;
  8. function btn_onclick()
  9. {
  10. var width;
  11. var Height;
  12. var canvas;
  13. var Xo,Yo;
  14. var k;
  15. canvas=document.getElementById("canvas");
  16. width=canvas.width;
  17. height=canvas.height;
  18. context=canvas.getContext('2d');
  19. Xo=width/2;
  20. Yo=height/2;
  21. k=parseInt(document.getElementById("drawType").value);
  22. if(k==2)
  23. A=Yo*0.25;
  24. else
  25. A=Yo*0.75;
  26. context.save();//保存当前绘制状态
  27. context.clearRect(0,0,width,height);//擦除之前绘制的图形
  28. context.translate(Xo,Yo);//坐标原点移动到canvas元素中央
  29. context.beginPath();//开始创建路径
  30. for(var B=0;B<=6.28;B=B+0.01)
  31. {
  32. draw(B);//绘制花朵曲线
  33. }
  34. context.closePath();//关闭路径
  35. context.restore();//恢复坐标轴平移之前的绘制状态
  36. }
  37. function draw(B)
  38. {
  39. var n=10;
  40. switch(parseInt(document.getElementById("drawType").value))
  41. {
  42. case 3://大丽花
  43. r=A*Math.sin(n*B)*Math.exp(-B/(20));
  44. break;
  45. case 2://令箭荷花
  46. r=A*(Math.sin(n*B)+3*Math.sin(3*n*B));
  47. break;
  48. case 1://蓬莱菊
  49. r=A*Math.sin(n*B);
  50. }
  51. //极坐标的直角坐标
  52. x=r*Math.cos(B);
  53. y=r*Math.sin(B);
  54. context.fillStyle="yellow";//设置填充颜色
  55. context.strokeStyle="black";//设置边框颜色
  56. context.lineTo(-x,-y);//绘制直线
  57. context.fill();//填充图形
  58. context.stroke();//绘制边框
  59. }
  60. </script>
  61. </head>
  62. <body>
  63. <h2>使用canvas元素绘制美丽的花朵</h2>
  64. 花的类型:
  65. <select id="drawType">
  66. <option value="1">蓬莱菊</option>
  67. <option value="2">令箭荷花</option>
  68. <option value="3">大丽花</option>
  69. </select>
  70. <input type="button" id="btn" value="绘制" onclick="btn_onclick()"/><br/>
  71. <canvas id="canvas" width="200px" height="200px"></canvas>
  72. </body>
  73. </html>

HTML5 canvas粒子烟花绽放动画

先给出演示图如下:

将下列代码保存为html文件名:HTML5canvas粒子烟花.HTML,用浏览器代开运行此文件,就可看到效果。

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>粒子烟花</title>
  6. <style>
  7. body {
  8. background-image: linear-gradient(6deg, #214, #000);
  9. background-size: 100% 100%;
  10. overflow:hidden
  11. }
  12. canvas { display: block; }
  13. </style>
  14. </head>
  15. <body>
  16. <script>
  17. class Vector2 {
  18. constructor(x = 0, y = 0) {
  19. this.x = x;
  20. this.y = y;
  21. }
  22. add(v) {
  23. this.x += v.x;
  24. this.y += v.y;
  25. return this;
  26. }
  27. multiplyScalar(s) {
  28. this.x *= s;
  29. this.y *= s;
  30. return this;
  31. }
  32. clone() {
  33. return new Vector2(this.x, this.y);
  34. }
  35. }
  36. class Time {
  37. constructor() {
  38. const now = Time.now();
  39. this.delta = 0;
  40. this.elapsed = 0;
  41. this.start = now;
  42. this.previous = now;
  43. }
  44. update() {
  45. const now = Time.now();
  46. this.delta = now - this.previous;
  47. this.elapsed = now - this.start;
  48. this.previous = now;
  49. }
  50. static now() {
  51. return Date.now() / 1000;
  52. }
  53. }
  54. class Particle {
  55. constructor(position, velocity = new Vector2, color = 'white', radius = 1, lifetime = 1, mass = 1) {
  56. this.position = position;
  57. this.velocity = velocity;
  58. this.color = color;
  59. this.radius = radius;
  60. this.lifetime = lifetime;
  61. this.mass = mass;
  62. this.isInCanvas = true;
  63. this.createdOn = Time.now();
  64. }
  65. update(time) {
  66. if (!this.getRemainingLifetime()) {
  67. return;
  68. }
  69. this.velocity.add(Particle.GRAVITATION.clone().multiplyScalar(this.mass));
  70. this.position.add(this.velocity.clone().multiplyScalar(time.delta));
  71. }
  72. render(canvas, context) {
  73. const remainingLifetime = this.getRemainingLifetime();
  74. if (!remainingLifetime) return;
  75. const radius = this.radius * remainingLifetime;
  76. context.globalAlpha = remainingLifetime;
  77. context.globalCompositeOperation = 'lighter';
  78. context.fillStyle = this.color;
  79. context.beginPath();
  80. context.arc(this.position.x, this.position.y, radius, 0, Math.PI * 2);
  81. context.fill();
  82. }
  83. getRemainingLifetime() {
  84. const elapsedLifetime = Time.now() - this.createdOn;
  85. return Math.max(0, this.lifetime - elapsedLifetime) / this.lifetime;
  86. }
  87. }
  88. Particle.GRAVITATION = new Vector2(0, 9.81);
  89. class Trail extends Particle {
  90. constructor(childFactory, position, velocity = new Vector2, lifetime = 1, mass = 1) {
  91. super(position, velocity);
  92. this.childFactory = childFactory;
  93. this.children = [];
  94. this.lifetime = lifetime;
  95. this.mass = mass;
  96. this.isAlive = true;
  97. }
  98. update(time) {
  99. super.update(time);
  100. // Add a new child on every frame
  101. if (this.isAlive && this.getRemainingLifetime()) {
  102. this.children.push(this.childFactory(this));
  103. }
  104. // Remove particles that are dead
  105. this.children = this.children.filter(function(child) {
  106. if (child instanceof Trail) {
  107. return child.isAlive;
  108. }
  109. return child.getRemainingLifetime();
  110. });
  111. // Kill trail if all particles fade away
  112. if (!this.children.length) {
  113. this.isAlive = false;
  114. }
  115. // Update particles
  116. this.children.forEach(function(child) {
  117. child.update(time);
  118. });
  119. }
  120. render(canvas, context) {
  121. // Render all children
  122. this.children.forEach(function(child) {
  123. child.render(canvas, context);
  124. });
  125. }
  126. }
  127. class Rocket extends Trail {
  128. constructor(childFactory, explosionFactory, position, velocity = new Vector2) {
  129. super(childFactory, position, velocity);
  130. this.explosionFactory = explosionFactory;
  131. this.lifetime = 10;
  132. }
  133. update(time) {
  134. if (this.getRemainingLifetime() && this.velocity.y > 0) {
  135. this.explosionFactory(this);
  136. this.lifetime = 0;
  137. }
  138. super.update(time);
  139. }
  140. }
  141. const canvas = document.createElement('canvas');
  142. const context = canvas.getContext('2d');
  143. const time = new Time;
  144. let rockets = [];
  145. const getTrustParticleFactory = function(baseHue) {
  146. function getColor() {
  147. const hue = Math.floor(Math.random() * 15 + 30);
  148. return `hsl(${hue}, 100%, 75%`;
  149. }
  150. return function(parent) {
  151. const position = this.position.clone();
  152. const velocity = this.velocity.clone().multiplyScalar(-.1);
  153. velocity.x += (Math.random() - .5) * 8;
  154. const color = getColor();
  155. const radius = 1 + Math.random();
  156. const lifetime = .5 + Math.random() * .5;
  157. const mass = .01;
  158. return new Particle(position, velocity, color, radius, lifetime, mass);
  159. };
  160. };
  161. const getExplosionFactory = function(baseHue) {
  162. function getColor() {
  163. const hue = Math.floor(baseHue + Math.random() * 15) % 360;
  164. const lightness = Math.floor(Math.pow(Math.random(), 2) * 50 + 50);
  165. return `hsl(${hue}, 100%, ${lightness}%`;
  166. }
  167. function getChildFactory() {
  168. return function(parent) {
  169. const direction = Math.random() * Math.PI * 2;
  170. const force = 8;
  171. const velocity = new Vector2(Math.cos(direction) * force, Math.sin(direction) * force);
  172. const color = getColor();
  173. const radius = 1 + Math.random();
  174. const lifetime = 1;
  175. const mass = .1;
  176. return new Particle(parent.position.clone(), velocity, color, radius, lifetime, mass);
  177. };
  178. }
  179. function getTrail(position) {
  180. const direction = Math.random() * Math.PI * 2;
  181. const force = Math.random() * 128;
  182. const velocity = new Vector2(Math.cos(direction) * force, Math.sin(direction) * force);
  183. const lifetime = .5 + Math.random();
  184. const mass = .075;
  185. return new Trail(getChildFactory(), position, velocity, lifetime, mass);
  186. }
  187. return function(parent) {
  188. let trails = 32;
  189. while (trails--) {
  190. parent.children.push(getTrail(parent.position.clone()));
  191. }
  192. };
  193. };
  194. const addRocket = function() {
  195. const trustParticleFactory = getTrustParticleFactory();
  196. const explosionFactory = getExplosionFactory(Math.random() * 360);
  197. const position = new Vector2(Math.random() * canvas.width, canvas.height);
  198. const thrust = window.innerHeight * .75;
  199. const angle = Math.PI / -2 + (Math.random() - .5) * Math.PI / 8;
  200. const velocity = new Vector2(Math.cos(angle) * thrust, Math.sin(angle) * thrust);
  201. const lifetime = 3;
  202. rockets.push(new Rocket(trustParticleFactory, explosionFactory, position, velocity, lifetime));
  203. rockets = rockets.filter(function(rocket) {
  204. return rocket.isAlive;
  205. });
  206. };
  207. const render = function() {
  208. requestAnimationFrame(render);
  209. time.update();
  210. context.clearRect(0, 0, canvas.width, canvas.height);
  211. rockets.forEach(function(rocket) {
  212. rocket.update(time);
  213. rocket.render(canvas, context);
  214. });
  215. };
  216. const resize = function() {
  217. canvas.height = window.innerHeight;
  218. canvas.width = window.innerWidth;
  219. };
  220. canvas.onclick = addRocket;
  221. document.body.appendChild(canvas);
  222. window.onresize = resize;
  223. resize();
  224. setInterval(addRocket, 250);
  225. render();
  226. </script>
  227. </body>
  228. </html>

HTML5 canva实现刮刮乐

先给出演示图如下:

准本几张素材图:

 源码如下:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>刮刮看(</title>
  6. <style>
  7. div.msg {
  8. font-family: 微软雅黑;
  9. color:#ffa502 ;
  10. }
  11. a:hover {
  12. color: rgb(0, 0, 0);
  13. text-decoration: none;
  14. }
  15. .btn-dang{
  16. border-radius: 8px;
  17. background-color: #21a3f1;
  18. color: rgb(255, 255, 255);
  19. }
  20. </style>
  21. </head>
  22. <body>
  23. <div id="main">
  24. <canvas
  25. id="myCanvas"
  26. width="400"
  27. height="400"
  28. style="border:1px solid #000;"
  29. >
  30. 您的浏览器不支持 HTML5 canvas 标签。
  31. </canvas>
  32. <div class="msg">
  33. <a
  34. href="javascript:void(0)"
  35. onClick="window.location.reload()"
  36. class="btn-dang"
  37. >随机换图</a
  38. >
  39. </div>
  40. </div>
  41. </body>
  42. <script>
  43. var mycanvas = document.getElementById("myCanvas");
  44. var ctx = mycanvas.getContext("2d");
  45. var arr = ["1.jpg", "2.jpg", "3.jpg"];
  46. var number = Math.floor(Math.random() * arr.length);
  47. var urla = "img/";
  48. mycanvas.style.background = "url(" + urla+arr[number] + ")";
  49. mycanvas.style.backgroundSize = "100%";
  50. ctx.fillStyle = "#cc6633";
  51. ctx.fillRect(0, 0, 10000,10000);
  52. ctx.font = "normal 80px 仿宋";
  53. ctx.strokeStyle = "slateblue";
  54. ctx.strokeText("请刮开!",80,150); //
  55. var status = "false";
  56. mycanvas.onmousedown = function () {
  57. status = "true";
  58. };
  59. mycanvas.onmouseup = function () {
  60. status = "false";
  61. };
  62. mycanvas.onmousemove = function (e) {
  63. if (status == "true") {
  64. ctx.globalCompositeOperation = "destination-out";
  65. ctx.beginPath();
  66. ctx.arc(e.pageX, e.pageY, 20, 0, 2 * Math.PI);
  67. ctx.closePath();
  68. ctx.fill();
  69. }
  70. };
  71. </script>
  72. </html>

HTML5 canva实现擦除上层图片的例子

先给出演示图如下:

准本几张素材图:

源码如下:

  1. <html lang="en">
  2. <head>
  3. <meta charset="UTF-8">
  4. <title>刮刮乐(实现擦除效果)</title>
  5. <style>
  6. *{
  7. margin: 0;
  8. padding: 0;
  9. box-sizing: border-box;
  10. }
  11. body{
  12. height: 100vh;
  13. display: flex;
  14. justify-content: center;
  15. align-items: center;
  16. }
  17. canvas{
  18. background-image: url('img/lower1.jpg'); //底层图片
  19. background-size: cover;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <canvas id="canvas"></canvas>
  25. <script>
  26. var canvas = document.querySelector("#canvas");
  27. var ctx = canvas.getContext("2d");
  28. canvas.width = 336;
  29. canvas.height = 410;
  30. var img = new Image();
  31. img.src = "img/upper1.jpg"; //上层图片,实现擦除效果
  32. img.onload=function(){
  33. ctx.drawImage(img,0,0,336,410);
  34. }
  35. canvas.addEventListener('mousemove',function(event){
  36. if(isDown){
  37. let x = event.offsetX;
  38. let y = event.offsetY;
  39. ctx.beginPath();
  40. ctx.fillStyle = "white";
  41. ctx.arc(x,y,20,Math.PI*2,false);
  42. ctx.fill();
  43. ctx.closePath();
  44. ctx.globalCompositeOperation = 'destination-out';
  45. }
  46. })
  47. var isDown = false;
  48. canvas.addEventListener('mousedown',function(){
  49. isDown = true;
  50. })
  51. canvas.addEventListener('mouseup',function(){
  52. isDown = false;
  53. })
  54. </script>
  55. </body>
  56. </html>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/85319
推荐阅读
相关标签
  

闽ICP备14008679号