{"id":28864,"date":"2024-04-09T21:57:16","date_gmt":"2024-04-09T20:57:16","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/creando-tu-primer-juego-con-html5-canvas-y-javascript\/"},"modified":"2024-06-03T17:42:59","modified_gmt":"2024-06-03T16:42:59","slug":"creando-tu-primer-juego-con-html5-canvas-y-javascript","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/creating-your-first-game-with-html5-canvas-and-javascript\/","title":{"rendered":"Creating your first game with HTML5 Canvas and JavaScript"},"content":{"rendered":"<p>Have you always wanted to create your own game, but don&#039;t know where to start? You&#039;re lucky! Today I&#039;m going to guide you through the exciting process of developing a simple game using HTML5 Canvas and JavaScript. You don&#039;t need to be an expert programmer to follow this tutorial; All you need is a little enthusiasm and desire to learn. In the end, you&#039;ll have a basic game running that you can proudly display.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ffffff;color:#ffffff\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewbox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ffffff;color:#ffffff\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewbox=\"0 0 24 24\" version=\"1.2\" baseprofile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/nelkodev.com\/en\/blog\/creating-your-first-game-with-html5-canvas-and-javascript\/#Introduccion_al_HTML5_Canvas\" >Introduction to HTML5 Canvas<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/nelkodev.com\/en\/blog\/creating-your-first-game-with-html5-canvas-and-javascript\/#Configurando_tu_Proyecto\" >Setting up your Project<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/blog\/creating-your-first-game-with-html5-canvas-and-javascript\/#Dando_vida_a_nuestro_Canvas\" >Giving life to our Canvas<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/blog\/creating-your-first-game-with-html5-canvas-and-javascript\/#Creando_un_Juego_Basico_Ping-Pong\" >Creating a Basic Game: Ping-Pong<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/creating-your-first-game-with-html5-canvas-and-javascript\/#Dibujando_la_Paleta_y_la_Pelota\" >Drawing the Paddle and the Ball<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/creating-your-first-game-with-html5-canvas-and-javascript\/#Animando_el_Juego\" >Animating the Game<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/creating-your-first-game-with-html5-canvas-and-javascript\/#Conclusiones_y_Pasos_Siguientes\" >Conclusions and Next Steps<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Introduccion_al_HTML5_Canvas\"><\/span>Introduction to HTML5 Canvas<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Before we dive into coding, it is crucial to understand what the HTML5 Canvas is and how it can help us in game development. Canvas provides a rectangular space on your web page where you can draw various graphics. This capability makes it ideal for rendering games, from simple puzzles to dynamic 2D shooters.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Configurando_tu_Proyecto\"><\/span>Setting up your Project<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>To get started, you need to have a text editor to write your code, such as Visual Studio Code, and a modern browser to view the results of your game. Create a new HTML file and name it <code>index.html<\/code>. Here is the basic skeleton of your HTML file:<\/p>\n<pre><code class=\"&quot;language-html&quot;\">&lt;!DOCTYPE html&gt;\n&lt;html lang=&quot;es&quot;&gt;\n&lt;head&gt;\n    &lt;meta charset=&quot;UTF-8&quot;&gt;\n    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;\n    &lt;title&gt;My First Game on Canvas&lt;\/title&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n    &lt;canvas id=&quot;gameCanvas&quot;&gt;&lt;\/canvas&gt;\n    &lt;script src=&quot;game.js&quot;&gt;&lt;\/script&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;<\/code><\/pre>\n<p>In this code, we have included an element <code>canvas<\/code> and an external JavaScript file called <code>game.js<\/code>, where we will put all the logic of our game.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Dando_vida_a_nuestro_Canvas\"><\/span>Giving life to our Canvas<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Go now to your new file <code>game.js<\/code> and let&#039;s start by writing some code to draw on the Canvas. The first thing is to obtain a reference to the canvas and its context, which we use to draw:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">const canvas = document.getElementById(&#039;gameCanvas&#039;); const ctx = canvas.getContext(&#039;2d&#039;); \/\/ We set the dimensions of the canvas canvas.width = 800; canvas.height = 600; \/\/ Draw a red rectangle ctx.fillStyle = &#039;red&#039;; ctx.fillRect(100, 100, 50, 50);<\/code><\/pre>\n<p>With these few lines of code, we set the size of our canvas and use the context to draw a simple red rectangle.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Creando_un_Juego_Basico_Ping-Pong\"><\/span>Creating a Basic Game: Ping-Pong<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>We are going to create a very basic version of the classic Ping-Pong game. For this, we need to draw the paddle, the ball and manage the logic to make them move.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Dibujando_la_Paleta_y_la_Pelota\"><\/span>Drawing the Paddle and the Ball<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>In <code>game.js<\/code>, you define some properties for the paddle and the ball, and create functions to draw them:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">\/\/ Palette properties const paddleWidth = 100; const paddleHeight = 20; let paddleX = (canvas.width - paddleWidth) \/ 2; let paddleY = canvas.height - paddleHeight; let paddleSpeed = 20; \/\/ Ball properties let ballX = canvas.width \/ 2; let ballY = canvas.height \/ 2; let ballRadius = 10; let ballSpeedX = 2; let ballSpeedY = -2; \/\/ Function to draw the palette function drawPaddle() { ctx.fillStyle = &#039;blue&#039;; ctx.fillRect(paddleX, paddleY, paddleWidth, paddleHeight); } \/\/ Function to draw the ball function drawBall() { ctx.beginPath(); ctx.arc(ballX, ballY, ballRadius, 0, Math.PI*2); ctx.fillStyle = &#039;black&#039;; ctx.fill(); ctx.closePath(); }<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Animando_el_Juego\"><\/span>Animating the Game<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>To make both the ball and the paddle move, we need to write a little more code. We are going to update the position of the ball and check if it collides with the walls of the canvas or with the paddle. Also, we must handle user input to move the palette:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">function updateGame() { \/\/ Update positions ballX += ballSpeedX; ballY += ballSpeedY; \/\/ Check for collision with walls if (ballY + ballSpeedY &lt; ballRadius || ballY + ballSpeedY &gt; canvas.height - ballRadius) { ballSpeedY = -ballSpeedY; } if (ballX + ballSpeedX &lt; ballRadius || ballX + ballSpeedX &gt; canvas.width - ballRadius) { ballSpeedX = -ballSpeedX; } \/\/ Draw everything ctx.clearRect(0, 0, canvas.width, canvas.height); drawPaddle(); drawBall(); \/\/ Request for the next animation frame requestAnimationFrame(updateGame); } updateGame(); \/\/ Keyboard event to move the paddle window.addEventListener(&#039;keydown&#039;, function(e) { if (e.key === &#039;ArrowLeft&#039; &amp;&amp; paddleX &gt; 0) { paddleX -= paddleSpeed; } else if ( e.key === &#039;ArrowRight&#039; &amp;&amp; paddleX &lt; canvas.width - paddleWidth) { paddleX += paddleSpeed;<\/code><\/pre>\n<p>With this, we now have a basic game working. The ball will bounce off the walls and you can move the paddle with the arrow keys on the keyboard.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Conclusiones_y_Pasos_Siguientes\"><\/span>Conclusions and Next Steps<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Congratulations! You&#039;ve created your first game using HTML5 Canvas and JavaScript. This is just the beginning. There are many ways you can expand this game. You could include a scoring system, increase the difficulty by adding more balls, or even create levels with different obstacles.<\/p>\n<p>If you are interested in continuing to learn about game development or any other topic related to programming, feel free to visit <a href=\"https:\/\/nelkodev.com\/en\/\">my blog<\/a> for more resources, or if you have any questions, you can always <a href=\"https:\/\/nelkodev.com\/en\/contact\/\">contact me<\/a>.<\/p>\n<p>Now, I encourage you to experiment with the code we have written. Modify the colors, sizes and speeds to see how you can make the game even more exciting. Have fun programming!<\/p>","protected":false},"excerpt":{"rendered":"<p>\u00bfSiempre has querido crear tu propio juego, pero no sabes por d\u00f3nde comenzar? \u00a1Est\u00e1s de suerte! Hoy te voy a guiar a trav\u00e9s del emocionante proceso de desarrollo de un juego simple utilizando HTML5 Canvas y JavaScript. No necesitas ser un experto programador para seguir este tutorial; lo \u00fanico que necesitas es un poco de [&hellip;]<\/p>","protected":false},"author":1,"featured_media":28865,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420],"tags":[205,1404,90,652,211,782,185,1986,99,529],"class_list":["post-28864","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","tag-blog","tag-canvas","tag-con","tag-creando","tag-desarrollo","tag-html5","tag-javascript","tag-juego","tag-juegos","tag-primer"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28864","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/comments?post=28864"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28864\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/28865"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=28864"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=28864"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=28864"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}