经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » 游戏设计 » 查看文章
通过游戏学javascript系列第一节Canvas游戏开发基础
来源:cnblogs  作者:师者乐享  时间:2020/12/14 17:03:01  对本文有异议

本节教程通过一个简单的游戏小例子,讲解Canvas的基础知识。

最终效果:

点击移动的方块,方块上的分数会增加,方块的行进方向会改变,并且方块的速度会增加。

在线演示

源码

HTML5引入了canvas元素。canvas元素为我们提供了一块空白画布。我们可以使用此画布来绘制和绘制我们想要的任何东西。JavaScript为我们提供了动态制作动画并绘制到画布上所需的工具。它不仅提供绘图和动画系统,还可以处理用户交互。在本教程中,我们将使用纯JavaScript制作基本的HTML5 Canvas框架,该框架可用于制作真实的游戏。在本教程的结尾创建了一个非常简单的游戏,以演示HTML5 Canvas与JavaScript结合的优势。

HTML5 Canvas基本游戏框架

让我们围绕canvas元素创建一个基本的游戏框架。我们需要一个HTML5文件和一个JavaScript文件。HTML5文件应包含canvas元素和对JavaScript文件的引用。JavaScript文件包含将代码绘制到canvas元素的代码。

这是HTML5文件index.html:

  1. <head>
  2. <meta charset="UTF-8">
  3. <title>Canvas Example</title>
  4. <script type="text/javascript" src="framework.js"></script>
  5. </head>
  6. <body>
  7. <canvas id="viewport" width="640" height="480"></canvas>
  8. </body>
  9. </html>

如您所见,JavaScript文件game.js包含在html文件的头部。画布元素以名称“ viewport”定义,其宽度为640像素,高度为480像素。在我们的framework.js中,我们需要使用其名称查找canvas元素,以便可以在其上进行绘制。我们正在创建的框架应支持渲染循环以及玩家与鼠标的交互。对于渲染循环,我们将使用Window.requestAnimationFrame()。通过添加鼠标事件侦听器来启用鼠标交互。

这是JavaScript文件framework.js:

  1. // The function gets called when the window is fully loaded
  2. window.onload = function() {
  3. // Get the canvas and context
  4. var canvas = document.getElementById("viewport");
  5. var context = canvas.getContext("2d");
  6. // Timing and frames per second
  7. var lastframe = 0;
  8. var fpstime = 0;
  9. var framecount = 0;
  10. var fps = 0;
  11. // Initialize the game
  12. function init() {
  13. // Add mouse events
  14. canvas.addEventListener("mousemove", onMouseMove);
  15. canvas.addEventListener("mousedown", onMouseDown);
  16. canvas.addEventListener("mouseup", onMouseUp);
  17. canvas.addEventListener("mouseout", onMouseOut);
  18. // Enter main loop
  19. main(0);
  20. }
  21. // Main loop
  22. function main(tframe) {
  23. // Request animation frames
  24. window.requestAnimationFrame(main);
  25. // Update and render the game
  26. update(tframe);
  27. render();
  28. }
  29. // Update the game state
  30. function update(tframe) {
  31. var dt = (tframe - lastframe) / 1000;
  32. lastframe = tframe;
  33. // Update the fps counter
  34. updateFps(dt);
  35. }
  36. function updateFps(dt) {
  37. if (fpstime > 0.25) {
  38. // Calculate fps
  39. fps = Math.round(framecount / fpstime);
  40. // Reset time and framecount
  41. fpstime = 0;
  42. framecount = 0;
  43. }
  44. // Increase time and framecount
  45. fpstime += dt;
  46. framecount++;
  47. }
  48. // Render the game
  49. function render() {
  50. // Draw the frame
  51. drawFrame();
  52. }
  53. // Draw a frame with a border
  54. function drawFrame() {
  55. // Draw background and a border
  56. context.fillStyle = "#d0d0d0";
  57. context.fillRect(0, 0, canvas.width, canvas.height);
  58. context.fillStyle = "#e8eaec";
  59. context.fillRect(1, 1, canvas.width-2, canvas.height-2);
  60. // Draw header
  61. context.fillStyle = "#303030";
  62. context.fillRect(0, 0, canvas.width, 65);
  63. // Draw title
  64. context.fillStyle = "#ffffff";
  65. context.font = "24px Verdana";
  66. context.fillText("HTML5 Canvas Basic Framework ", 10, 30);
  67. // Display fps
  68. context.fillStyle = "#ffffff";
  69. context.font = "12px Verdana";
  70. context.fillText("Fps: " + fps, 13, 50);
  71. }
  72. // Mouse event handlers
  73. function onMouseMove(e) {}
  74. function onMouseDown(e) {}
  75. function onMouseUp(e) {}
  76. function onMouseOut(e) {}
  77. // Get the mouse position
  78. function getMousePos(canvas, e) {
  79. var rect = canvas.getBoundingClientRect();
  80. return {
  81. x: Math.round((e.clientX - rect.left)/(rect.right - rect.left)*canvas.width),
  82. y: Math.round((e.clientY - rect.top)/(rect.bottom - rect.top)*canvas.height)
  83. };
  84. }
  85. // Call init to start the game
  86. init();
  87. };

上面的代码绘制了一个带有边框,标题和每秒帧数的简单框架。这是代码生成的内容

带有弹跳方块的游戏

现在我们有了一个框架,让我们用它创建一个简单的游戏。我们将创建一个在屏幕上具有反弹方块的游戏。当玩家单击它时,方块上的分数会增加,方块的行进方向会改变,并且方块的速度会增加。

首先,我们定义一些对象和属性。该级别定义了方块可以反弹的区域。方块本身具有位置,尺寸和运动属性。最后,有一个分数。

  1. // Level properties
  2. var level = {
  3. x: 1,
  4. y: 65,
  5. width: canvas.width - 2,
  6. height: canvas.height - 66
  7. };
  8. // Square
  9. var square = {
  10. x: 0,
  11. y: 0,
  12. width: 0,
  13. height: 0,
  14. xdir: 0,
  15. ydir: 0,
  16. speed: 0
  17. }
  18. // Score
  19. var score = 0;

我们需要在init()函数中初始化对象和属性。

  1. // Initialize the game
  2. function init() {
  3. // Add mouse events
  4. canvas.addEventListener("mousemove", onMouseMove);
  5. canvas.addEventListener("mousedown", onMouseDown);
  6. canvas.addEventListener("mouseup", onMouseUp);
  7. canvas.addEventListener("mouseout", onMouseOut);
  8. // Initialize the square
  9. square.width = 100;
  10. square.height = 100;
  11. square.x = level.x + (level.width - square.width) / 2;
  12. square.y = level.y + (level.height - square.height) / 2;
  13. square.xdir = 1;
  14. square.ydir = 1;
  15. square.speed = 200;
  16. // Initialize the score
  17. score = 0;
  18. // Enter main loop
  19. main(0);
  20. }

这些对象需要更新,因此让我们修改update()函数。方块需要移动,并且应该检测并解决与标高边缘的碰撞。

  1. // Update the game state
  2. function update(tframe) {
  3. var dt = (tframe - lastframe) / 1000;
  4. lastframe = tframe;
  5. // Update the fps counter
  6. updateFps(dt);
  7. // Move the square, time-based
  8. square.x += dt * square.speed * square.xdir;
  9. square.y += dt * square.speed * square.ydir;
  10. // Handle left and right collisions with the level
  11. if (square.x <= level.x) {
  12. // Left edge
  13. square.xdir = 1;
  14. square.x = level.x;
  15. } else if (square.x + square.width >= level.x + level.width) {
  16. // Right edge
  17. square.xdir = -1;
  18. square.x = level.x + level.width - square.width;
  19. }
  20. // Handle top and bottom collisions with the level
  21. if (square.y <= level.y) {
  22. // Top edge
  23. square.ydir = 1;
  24. square.y = level.y;
  25. } else if (square.y + square.height >= level.y + level.height) {
  26. // Bottom edge
  27. square.ydir = -1;
  28. square.y = level.y + level.height - square.height;
  29. }
  30. }

我们需要绘制方块和分数。这需要在render()函数中完成。

  1. // Render the game
  2. function render() {
  3. // Draw the frame
  4. drawFrame();
  5. // Draw the square
  6. context.fillStyle = "#ff8080";
  7. context.fillRect(square.x, square.y, square.width, square.height);
  8. // Draw score inside the square
  9. context.fillStyle = "#ffffff";
  10. context.font = "38px Verdana";
  11. var textdim = context.measureText(score);
  12. context.fillText(score, square.x+(square.width-textdim.width)/2, square.y+65);
  13. }

最后一步是添加鼠标交互。让我们将代码添加到onMouseDown()函数中。

  1. function onMouseDown(e) {
  2. // Get the mouse position
  3. var pos = getMousePos(canvas, e);
  4. // Check if we clicked the square
  5. if (pos.x >= square.x && pos.x < square.x + square.width &&
  6. pos.y >= square.y && pos.y < square.y + square.height) {
  7. // Increase the score
  8. score += 1;
  9. // Increase the speed of the square by 10 percent
  10. square.speed *= 1.1;
  11. // Give the square a random position
  12. square.x = Math.floor(Math.random()*(level.x+level.width-square.width));
  13. square.y = Math.floor(Math.random()*(level.y+level.height-square.height));
  14. // Give the square a random direction
  15. square.xdir = Math.floor(Math.random() * 2) * 2 - 1;
  16. square.ydir = Math.floor(Math.random() * 2) * 2 - 1;
  17. }
  18. }

这是通过基本框架和一些修改而成的最终游戏。单击方块以增加您的分数并前进到下一个方块。

原文链接:http://www.cnblogs.com/neuedu/p/javascript-game-canvas.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号