{"id":28775,"date":"2024-04-09T19:42:07","date_gmt":"2024-04-09T18:42:07","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/domina-los-graficos-dinamicos-con-canvas-y-javascript\/"},"modified":"2024-06-03T17:42:25","modified_gmt":"2024-06-03T16:42:25","slug":"domina-los-graficos-dinamicos-con-canvas-y-javascript","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/master-dynamic-graphics-with-canvas-and-javascript\/","title":{"rendered":"Master Dynamic Charts with Canvas and JavaScript"},"content":{"rendered":"<p>The element <code>canvas<\/code> HTML5 has revolutionized the way developers can create dynamic, visually stunning graphics directly on the web, using only HTML and JavaScript. This resource is incredibly powerful for data visualizations, games, animations, and any type of interactive digital art. In this post, I&#039;ll walk you through the basics of drawing and animating on an HTML5 canvas, showing you each step with practical examples that you can try and modify.<\/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\/master-dynamic-graphics-with-canvas-and-javascript\/#Entendiendo_el_Elemento_Canvas\" >Understanding the Canvas Element<\/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\/master-dynamic-graphics-with-canvas-and-javascript\/#Como_Configurar_Tu_Canvas\" >How to Set Up Your Canvas<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-dynamic-graphics-with-canvas-and-javascript\/#Dibujando_Formas_Basicas\" >Drawing Basic Shapes<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-dynamic-graphics-with-canvas-and-javascript\/#Lineas_y_Curvas\" >Lines and Curves<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-dynamic-graphics-with-canvas-and-javascript\/#Animando_en_Canvas\" >Animating on Canvas<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-dynamic-graphics-with-canvas-and-javascript\/#Consejos_para_Mejorar_tus_Animaciones\" >Tips to Improve your Animations<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-dynamic-graphics-with-canvas-and-javascript\/#Uso_de_requestAnimationFrame\" >Using requestAnimationFrame<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-dynamic-graphics-with-canvas-and-javascript\/#Temporizacion_y_Control_de_Velocidad\" >Timing and Speed Control<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-dynamic-graphics-with-canvas-and-javascript\/#Pruebas_y_Optimizacion\" >Testing and Optimization<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/nelkodev.com\/en\/blog\/master-dynamic-graphics-with-canvas-and-javascript\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Entendiendo_el_Elemento_Canvas\"><\/span>Understanding the Canvas Element<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The element <code>canvas<\/code> It is a blank container that, by itself, shows nothing. To paint something on it, you need to use a rendering context, which is usually the &quot;2d&quot; context. This context provides functions for drawing text, lines, curves, areas, and more.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Como_Configurar_Tu_Canvas\"><\/span>How to Set Up Your Canvas<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>First, you need to add the element <code>canvas<\/code> in your HTML:<\/p>\n<pre><code class=\"&quot;language-html&quot;\">&lt;canvas id=&quot;miCanvas&quot; width=&quot;800&quot; height=&quot;600&quot;&gt;&lt;\/canvas&gt;<\/code><\/pre>\n<p>Be sure to assign a <code>id<\/code> unique and specify the dimensions of the canvas. Then in your JavaScript you can get the 2d context like this:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">var canvas = document.getElementById(&#039;myCanvas&#039;); var ctx = canvas.getContext(&#039;2d&#039;);<\/code><\/pre>\n<p>With the context obtained, you are now ready to draw.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Dibujando_Formas_Basicas\"><\/span>Drawing Basic Shapes<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Let&#039;s start with something simple: draw a rectangle.<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">ctx.fillStyle = &#039;blue&#039;; \/\/ Set the fill color to blue ctx.fillRect(50, 50, 200, 150); \/\/ Draw a rectangle<\/code><\/pre>\n<p>The coordinates <code>(50, 50)<\/code> specify the top left position of the rectangle on the canvas, and <code>(200, 150)<\/code> are the width and height of the rectangle, respectively.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Lineas_y_Curvas\"><\/span>Lines and Curves<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Drawing lines and curves is equally simple:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">\/\/ Draw a line ctx.beginPath(); ctx.moveTo(100, 100); \/\/ Move to the initial position ctx.lineTo(300, 100); \/\/ Draw a line to this position ctx.stroke(); \/\/ End the trace \/\/ Draw a bezier curve ctx.beginPath(); ctx.moveTo(100, 300); ctx.bezierCurveTo(150, 200, 250, 400, 300, 300); ctx.stroke(); \/\/ End the stroke<\/code><\/pre>\n<p>Now that you know how to draw basic elements, let&#039;s talk about animation.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Animando_en_Canvas\"><\/span>Animating on Canvas<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Canvas animation is achieved by redrawing the canvas at regular intervals, typically using <code>requestAnimationFrame<\/code>. Here I show you how to make a simple square that moves along the canvas:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">var x = 0; function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); \/\/ Clear the canvas ctx.fillStyle = &#039;red&#039;; ctx.fillRect(x, 100, 50, 50); \/\/ Draw a square in new position x += 2; \/\/ Change the position for the next frame if (x &lt; canvas.width) { requestAnimationFrame(animate); \/\/ Continue animation } } animate();<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Consejos_para_Mejorar_tus_Animaciones\"><\/span>Tips to Improve your Animations<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"Uso_de_requestAnimationFrame\"><\/span>Use of <code>requestAnimationFrame<\/code><span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>It is preferable over <code>setTimeout<\/code> o <code>setInterval<\/code> because it is optimized for animations, running just before each repaint, leading to smoother and more efficient animations.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Temporizacion_y_Control_de_Velocidad\"><\/span>Timing and Speed Control<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>You can use <code>Date.now()<\/code> to control the speed of the animation, adjusting movement based on the actual time that has passed, rather than frames. This ensures that your animation runs at the same speed, regardless of hardware specifications.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Pruebas_y_Optimizacion\"><\/span>Testing and Optimization<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Test your animation on different devices and browsers to make sure it looks the way you expect. Use development tools to measure and optimize performance.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>He <code>canvas<\/code> HTML5 is an extremely powerful tool for web developers who want to incorporate dynamic graphics and animations into their projects. Not only is it fun to use, but it also allows you to create rich, interactive experiences for users. By mastering basic drawing and animation techniques, and experimenting with their various possibilities, you will be able to significantly raise the visual quality of your web applications.<\/p>\n<p>If you have any questions or need help implementing these techniques in your own projects, feel free to visit my contact page at <a href=\"https:\/\/nelkodev.com\/en\/contact\/\">NelkoDev Contact<\/a>. I&#039;m here to help you create something amazing!<\/p>","protected":false},"excerpt":{"rendered":"<p>El elemento canvas de HTML5 ha revolucionado la manera en que los desarrolladores pueden crear gr\u00e1ficos din\u00e1micos y visualmente impresionantes directamente en la web, utilizando s\u00f3lo HTML y JavaScript. Este recurso es incre\u00edblemente poderoso para visualizaciones de datos, juegos, animaciones y cualquier tipo de arte digital interactivo. En esta publicaci\u00f3n, te guiar\u00e9 a trav\u00e9s de [&hellip;]<\/p>","protected":false},"author":1,"featured_media":28776,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420,1939],"tags":[205,1404,90,491,1473,2205,1365,185,221,1008],"class_list":["post-28775","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","category-pruebas-de-frontend","tag-blog","tag-canvas","tag-con","tag-dinamicos","tag-domina","tag-frontend","tag-graficos","tag-javascript","tag-los","tag-pruebas"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28775","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=28775"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28775\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/28776"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=28775"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=28775"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=28775"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}