<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ canvas - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ canvas - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 31 May 2026 14:26:30 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/canvas/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to use the Fullscreen API in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ How do you run a game created for the web in fullscreen? In this quick tutorial, you'll see how to display a game or any other HTML element in fullscreen, how to exit fullscreen, and how to make a nice fullscreen toggle button in SVG. Recently I publ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-use-full-screen-api-in-js/</link>
                <guid isPermaLink="false">66c4c81129f446a67a4197ee</guid>
                
                    <category>
                        <![CDATA[ Fullscreen API ]]>
                    </category>
                
                    <category>
                        <![CDATA[ canvas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SVG ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Hunor Márton Borbély ]]>
                </dc:creator>
                <pubDate>Thu, 22 Feb 2024 14:17:32 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Untitled.022.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>How do you run a game created for the web in fullscreen? In this quick tutorial, you'll see how to display a game or any other HTML element in fullscreen, how to exit fullscreen, and how to make a nice fullscreen toggle button in SVG.</p>
<p>Recently I published a long <a target="_blank" href="https://www.freecodecamp.org/news/how-to-draw-a-gorilla-with-javascript-on-html-canvas/">JavaScript game tutorial</a>. While it was a very packed guide, there were still a few things we could not cover in it: how to display the game in fullscreen.</p>
<p>When you watch a video on YouTube, you have the option to also watch it on fullscreen. But did you know that the fullscreen feature isn't only for video elements?</p>
<p>In JavaScript, there’s a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API">Fullscreen API</a>. And it’s surprisingly simple to use. Here's a quick demo of what we're about to implement. Let's see how it works.</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/HunorMarton/embed/QWoRLXM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p>You can also <a target="_blank" href="https://www.youtube.com/watch?v=jX3mIQdQQ2w&amp;t=15s">watch this article as a video</a> on YouTube.</p>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-enter-fullscreen-mode">How to Enter Fullscreen Mode</a></li>
<li><a class="post-section-overview" href="#heading-how-to-style-the-fullscreen">How to Style the Fullscreen</a></li>
<li><a class="post-section-overview" href="#heading-how-to-display-games-with-the-canvas-element-in-fullscreen">How to Display Games with the Canvas Element in Fullscreen</a></li>
<li><a class="post-section-overview" href="#heading-how-to-exit-fullscreen">How to Exit Fullscreen</a></li>
<li><a class="post-section-overview" href="#heading-how-to-code-a-fullscreen-icon-with-svg">How to Code a Fullscreen Icon with SVG</a></li>
<li><a class="post-section-overview" href="#heading-learn-more">Learn More</a></li>
</ul>
<h2 id="heading-how-to-enter-fullscreen-mode">How to Enter Fullscreen Mode</h2>
<p>Let’s say we have a simple website with some text. And at the bottom, we have a button that will display the text in full screen. We are going to refine the look of this button, but first, let’s get work on the main logic.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-21-at-18.20.51.png" alt="Image" width="600" height="400" loading="lazy">
<em>A simple website with some text and a Toggle Fullscreen button</em></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">font-family</span>: Montserrat;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">max-width</span>: <span class="hljs-number">500px</span>;
}
</code></pre>
<p>In the code above, we attached an event handler to the button in HTML. We can then implement the <code>toggleFullscreen</code> function logic in JavaScript.</p>
<p>In this function, all we have to do is call the <code>requestFullScreen</code> method on the <code>document</code>’s <code>documentElement</code> property. And that’s it:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">toggleFullscreen</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">document</span>.documentElement.requestFullscreen();
}
</code></pre>
<p>If you click the button, your website will pop into fullscreen.</p>
<h2 id="heading-how-to-style-the-fullscreen">How to Style the Fullscreen</h2>
<p>Before we cover how to exit full screen and create a nice-looking toggle button, let’s see a few other things.</p>
<p>What you might notice right away is that, with more space, your content might get a bit lost on a full screen. Make sure you have a responsive styling that looks good on every screen size.</p>
<p>You can even style the layout specifically for fullscreen. In CSS you can set a media query that only applies the styling in case the <code>display-mode</code> is <code>fullscreen</code>. </p>
<p>For instance, you can change the font-size, or change the <code>background-color</code> to have a distinct look on full screen.</p>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> (<span class="hljs-attribute">display-mode:</span> fullscreen) {
  <span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f9bb86</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.2em</span>;
  }
}
</code></pre>
<h2 id="heading-how-to-display-games-with-the-canvas-element-in-fullscreen">How to Display Games with the Canvas Element in Fullscreen</h2>
<p>In this case, we want to make a game that uses the <code>canvas</code> element to be fullscreen – like the <a target="_blank" href="https://www.freecodecamp.org/news/how-to-draw-a-gorilla-with-javascript-on-html-canvas/">Gorillas</a> game – we also need to resize the <code>canvas</code> element to fit the whole screen.</p>
<p>In this case, we can use the <code>windows</code>’s <code>resize</code> event. The event is triggered both when we simply resize the browser window, and when we enter or exit fullscreen mode. </p>
<p>With the <code>resize</code> event, we can resize the <code>canvas</code> element to fit the whole screen, update the scaling, adjust any other properties we need to change on resize and redraw the whole scene.</p>
<pre><code class="lang-js"><span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"resize"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// Resize canvas element</span>
  canvas.width = <span class="hljs-built_in">window</span>.innerWidth;
  canvas.height = <span class="hljs-built_in">window</span>.innerHeight;

  <span class="hljs-comment">// Update scaling</span>
  <span class="hljs-comment">// . . .</span>

  <span class="hljs-comment">// Adjust size dependent properties</span>
  <span class="hljs-comment">// . . .</span>

  <span class="hljs-comment">// Redraw canvas</span>
  draw();
});
</code></pre>
<p>If you check the source code of the <a target="_blank" href="https://codepen.io/HunorMarton/pen/jOJZqvp">Gorillas game on CodePen</a>, you'll find similar steps.</p>
<h2 id="heading-how-to-exit-fullscreen">How to Exit Fullscreen</h2>
<p>Now that we know how to enter full screen, how do we exit from it?</p>
<p>By default, if you press the <code>Escape</code> key, the browser switches back to the normal view. In Google Chrome, you even get a notification at the top of the screen about this when you enter fullscreen mode.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-21-at-17.47.03-2.png" alt="Image" width="600" height="400" loading="lazy">
<em>Google Chrome shows a notification on top of the screen once you enter full screen</em></p>
<p>What if you want to exit fullscreen mode when you click the HTML button? Let’s change our button’s behavior to toggle fullscreen on or off.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">toggleFullscreen</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">document</span>.fullscreenElement) {
    <span class="hljs-built_in">document</span>.documentElement.requestFullscreen();
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">document</span>.exitFullscreen();
  }
}
</code></pre>
<p>First, we start by checking if we are in fullscreen mode already. We can do this by checking the <code>document</code>’s <code>fullscreenElement</code> property. If it is undefined, then we enter fullscreen mode the same way we did before. And if we are already in fullscreen mode, then we can exit by calling the document’s <code>exitFullscreen</code> method. </p>
<p>It is really that simple. With a few lines of code, we can implement the logic for a fullscreen toggle button.</p>
<h2 id="heading-how-to-code-a-fullscreen-icon-with-svg">How to Code a Fullscreen Icon with SVG</h2>
<p>If you follow <a target="_blank" href="https://www.freecodecamp.org/news/author/hunor/">my tutorials</a>, you know I love creative coding, and <a target="_blank" href="https://www.freecodecamp.org/news/svg-tutorial-learn-to-code-images/">drawing from code</a>. So let’s update the look of our button, to make it look similar to what we have on YouTube.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-21-at-18.06.07.png" alt="Image" width="600" height="400" loading="lazy">
<em>Fullscreen icon</em></p>
<p>Let’s create an SVG image within our button. If you check the source code of YouTube, you will see that they also use an SVG.</p>
<p>Let’s define an SVG element within HTML. We'll set its size to 30 x 30 and define a <code>path</code> element:</p>
<pre><code class="lang-html">. . .

<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"toggleFullscreen()"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">width</span>=<span class="hljs-string">"30"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"30"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">path</span>
      <span class="hljs-attr">stroke</span>=<span class="hljs-string">"black"</span>
      <span class="hljs-attr">stroke-width</span>=<span class="hljs-string">"3"</span>
      <span class="hljs-attr">fill</span>=<span class="hljs-string">"none"</span>
      <span class="hljs-attr">d</span>=<span class="hljs-string">"
        M 10, 2 L 2,2 L 2, 10
        M 20, 2 L 28,2 L 28, 10
        M 28, 20 L 28,28 L 20, 28
        M 10, 28 L 2,28 L 2, 20"</span>
    /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

. . .
</code></pre>
<p>To style the path, we set its color with the <code>stroke</code> property, set its <code>stroke-width</code>, and made sure that we didn't end up with a filled shape. SVG paths by default are filled, so we need to set explicitly that we don’t want to <code>fill</code> this shape.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-21-at-18.02.10.png" alt="Image" width="600" height="400" loading="lazy">
<em>Using the move-to and line-to commands within an SVG path</em></p>
<p>Then we defined the path with a few move-to and line-to commands. We can set these commands as a string in the <code>d</code> attribute of the path element.</p>
<p>We started with a move-to command: <code>M 10, 2</code>. The letter <code>M</code> signifies that we have a move-to command, and the 10 and 2 are the <code>x</code> and <code>y</code> coordinates of this command. We moved to the start of one of the four lines.</p>
<p>Then we continued the path with a line-to command that moves to the corner, and then with another line-to command. The line-to command works in a similar way. It starts with the letter <code>L</code>, then we set an <code>x, y</code> coordinates where the line should go to.</p>
<p>Then we did the same with the other corners. We move to the next line segment with another move-to command and draw a line with two more line-to commands.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Untitled.021.png" alt="Image" width="600" height="400" loading="lazy">
<em>Drawing a path on a Canvas element with JavaScript has some similarities to defining a path in SVG</em></p>
<p><strong>Note</strong>: If you read my <a target="_blank" href="https://www.freecodecamp.org/news/how-to-draw-a-gorilla-with-javascript-on-html-canvas/">previous tutorial</a> on how to make the gorillas game, then you might have noticed that we had something similar there. We also drew paths with move to and line to. Except that there we were drawn on a <code>canvas</code> element with JavaScript, and now we have the commands as a string within the HTML file.</p>
<h3 id="heading-how-to-toggle-the-icons-appearance">How to Toggle the Icon's Appearance</h3>
<p>Now the SVG is looking great, but what if we want to have a different look when we are in fullscreen mode? On YouTube, when we enter fullscreen mode, the button switches to a different icon.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-21-at-18.06.33.png" alt="Image" width="600" height="400" loading="lazy">
<em>The two faces of the fullscreen icon</em></p>
<p>You can do this in different ways. The easiest way is probably to define another path, within the same SVG element with a different look. Then make this path transparent by default. We are going to toggle the visibility of these two paths in JavaScript.</p>
<pre><code class="lang-html">. . .

<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"toggleFullscreen()"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">width</span>=<span class="hljs-string">"30"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"30"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">path</span>
      <span class="hljs-attr">id</span>=<span class="hljs-string">"enter-fullscreen"</span>
      <span class="hljs-attr">stroke</span>=<span class="hljs-string">"black"</span>
      <span class="hljs-attr">stroke-width</span>=<span class="hljs-string">"3"</span>
      <span class="hljs-attr">fill</span>=<span class="hljs-string">"none"</span>
      <span class="hljs-attr">d</span>=<span class="hljs-string">"
        M 10, 2 L 2,2 L 2, 10
        M 20, 2 L 28,2 L 28, 10
        M 28, 20 L 28,28 L 20, 28
        M 10, 28 L 2,28 L 2, 20"</span>
    /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">path</span>
      <span class="hljs-attr">id</span>=<span class="hljs-string">"exit-fullscreen"</span>
      <span class="hljs-attr">stroke</span>=<span class="hljs-string">"transparent"</span>
      <span class="hljs-attr">stroke-width</span>=<span class="hljs-string">"3"</span>
      <span class="hljs-attr">fill</span>=<span class="hljs-string">"none"</span>
      <span class="hljs-attr">d</span>=<span class="hljs-string">"
        M 10, 2 L 10,10 L 2, 10
        M 20, 2 L 20,10 L 28, 10
        M 28, 20 L 20,20 L 20, 28
        M 10, 28 L 10,20 L 2, 20"</span>
    /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

. . .
</code></pre>
<p>This second path is very similar to the previous one. Except that we used different coordinates for some of the line-to commands.</p>
<p>Then we set unique IDs for both of these paths, and we update our toggle function in JavaScript. In JavaScript, we get a reference to these paths by ID, and then in the toggle button’s event handler, we can switch the visibility of these elements back and forth.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> enterFullscreen = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"enter-fullscreen"</span>);
<span class="hljs-keyword">const</span> exitFullscreen = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"exit-fullscreen"</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">toggleFullscreen</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">document</span>.fullscreenElement) {
    <span class="hljs-built_in">document</span>.documentElement.requestFullscreen();
    enterFullscreen.setAttribute(<span class="hljs-string">"stroke"</span>, <span class="hljs-string">"transparent"</span>);
    exitFullscreen.setAttribute(<span class="hljs-string">"stroke"</span>, <span class="hljs-string">"black"</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">document</span>.exitFullscreen();
    enterFullscreen.setAttribute(<span class="hljs-string">"stroke"</span>, <span class="hljs-string">"black"</span>);
    exitFullscreen.setAttribute(<span class="hljs-string">"stroke"</span>, <span class="hljs-string">"transparent"</span>);
  }
}
</code></pre>
<p>Now if you click this button, it toggles the fullscreen mode and changes its own appearance.</p>
<h2 id="heading-learn-more">Learn More</h2>
<p>If you want to learn more about SVGs, check out <a target="_blank" href="http://SVG-Tutorial.com">SVG-Tutorial.com</a> where you can find a lot of examples from the basics to more advanced levels. It’s a free site and you can also find the example that we discussed in this article.</p>
<p>To use the button to run a JavaScript game in full screen, check out the whole JavaScript Game Tutorial on how to remake the classic Gorillas game here on <a target="_blank" href="https://www.freecodecamp.org/news/how-to-draw-a-gorilla-with-javascript-on-html-canvas/">freeCodeCamp</a> or on <a target="_blank" href="https://www.youtube.com/watch?v=2q5EufbUEQk&amp;t=2337s">YouTube</a>. It’s a massive tutorial that covers things from drawing on an HTML Canvas element, to the entire game logic, from event handling, through the animation loop, hit detection, and even AI logic, for the enemy gorilla.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/2q5EufbUEQk" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>You can subscribe to my channel for more JavaScript game development tutorials:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/undefined" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Draw with JavaScript on an HTML Canvas Element – Gorilla Example ]]>
                </title>
                <description>
                    <![CDATA[ Drawing from code can be fun for many reasons. You can generate art that follows a certain logic. You can create animations by moving only parts of an image. And you can even build up a whole game as I covered in this tutorial. In my last article, we... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-draw-a-gorilla-with-javascript-on-html-canvas/</link>
                <guid isPermaLink="false">66c4c80829f446a67a4197ec</guid>
                
                    <category>
                        <![CDATA[ canvas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Hunor Márton Borbély ]]>
                </dc:creator>
                <pubDate>Thu, 15 Feb 2024 16:30:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Thumbnail.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Drawing from code can be fun for many reasons. You can generate art that follows a certain logic. You can create animations by moving only parts of an image. And you can even build up a whole game as I covered in <a target="_blank" href="https://www.freecodecamp.org/news/gorillas-game-in-javascript/">this tutorial</a>.</p>
<p>In my last article, we focused on the <a target="_blank" href="https://www.freecodecamp.org/news/drawing-on-a-canvas-element-with-javascript/">basics of drawing</a>. Now, let's see a concrete example and explore how to use JavaScript to draw a Gorilla. </p>
<p>You don't need to have any prerequisites for this tutorial. Even if you missed the basics, you can start right away. We are only going to have some simple HTML and a plain JavaScript file that you can run directly in the browser.</p>
<p>By the end, you'll know how to draw a gorilla with JS.‌</p>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ol>
<li><a class="post-section-overview" href="#heading-how-to-define-a-canvas">How to Define a Canvas</a></li>
<li><a class="post-section-overview" href="#heading-how-to-turn-the-coordinate-system-upside-down">How to Turn the Coordinate System Upside Down</a></li>
<li><a class="post-section-overview" href="#heading-how-to-draw-the-legs-of-the-gorilla">How to Draw the Body of the Gorilla</a></li>
<li><a class="post-section-overview" href="#heading-how-to-draw-the-arms-of-the-gorilla">How to Draw the Legs of the gorilla</a></li>
<li><a class="post-section-overview" href="#heading-how-to-draw-the-face-of-the-gorilla">How to Draw the Arms of the Gorilla</a></li>
<li><a class="post-section-overview" href="#heading-how-to-draw-the-face-of-the-gorilla">How to Draw the Face of the Gorilla</a></li>
<li><a class="post-section-overview" href="#heading-next-steps">Next Steps</a></li>
</ol>
<h2 id="heading-how-to-define-a-canvas">How to Define a Canvas</h2>
<p>To draw our gorilla, first let's define a simple HTML file with a Canvas element. Then we'll see how to access it from JavaScript. </p>
<p>In the HTML file, in the header, we'll add our JavaScript file. Note that I’m using the <code>defer</code> keyword to make sure the script only executes once the rest of the document is parsed.</p>
<p>In the body, we'll add a <code>canvas</code> element. We set its size to 500 x 500 and set an ID.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Gorilla<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"index.js"</span> <span class="hljs-attr">defer</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">canvas</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"gorilla"</span> <span class="hljs-attr">width</span>=<span class="hljs-string">"500"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"500"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">canvas</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Then, let's create a JavaScript file. In this file, we'll first get the canvas element by ID. Then, we'll get the rendering context of the canvas element. This is a built-in API with many methods and properties that we can use to draw on the canvas.</p>
<pre><code class="lang-js"><span class="hljs-comment">// The canvas element and its drawing context </span>
<span class="hljs-keyword">const</span> canvas = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"gorilla"</span>); 
<span class="hljs-keyword">const</span> ctx = canvas.getContext(<span class="hljs-string">"2d"</span>);

. . .
</code></pre>
<p>Before we get to drawing, first let's make our life easier by turning the coordinate system upside down.</p>
<h2 id="heading-how-to-turn-the-coordinate-system-upside-down">How to Turn the Coordinate System Upside Down</h2>
<p>When we use canvas, we have a coordinate system with the origin at the top-left corner of the canvas that grows to the right and downwards. This is aligned with how websites work in general. Things go from left to right and top to bottom. </p>
<p>This is the default, but we can change it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/08/gorilla-with-and-without-transforming-and-scaling.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>The gorilla with and without transforming and scaling the coordinate system</em></p>
<p>In our case, it is more convenient to go from the bottom to the top. Then the gorilla can stand at the bottom, and we don’t have to figure out where the bottom of the canvas is.</p>
<p>We can use the <code>translate</code> method to shift the entire coordinate system to the bottom-middle of the canvas. We'll move the coordinate system down along the Y-axis by the size of the canvas, and to the right along the X-axis by half the size of the canvas.</p>
<p>Once we do this, the Y-coordinate is still growing downwards. We can flip it using the <code>scale</code> method. Setting a negative number for the vertical direction will flip the entire coordinate system upside down.</p>
<pre><code class="lang-js"><span class="hljs-comment">// The canvas element and its drawing context </span>
<span class="hljs-keyword">const</span> canvas = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"gorilla"</span>); 
<span class="hljs-keyword">const</span> ctx = canvas.getContext(<span class="hljs-string">"2d"</span>);

ctx.translate(<span class="hljs-number">250</span>, <span class="hljs-number">500</span>);
ctx.scale(<span class="hljs-number">1</span>, <span class="hljs-number">-1</span>);

. . .
</code></pre>
<p>‌We have to do this before we paint anything on the canvas because the <code>translate</code> and <code>scale</code> methods do not actually move anything that's already on the canvas. But anything we paint after these method calls will be painted according to this new coordinate system.</p>
<h2 id="heading-how-to-draw-the-gorilla">How to Draw the Gorilla</h2>
<p>Now let's look into drawing the gorilla. We'll break this down into multiple steps. First, we'll draw the body, then the legs, the arms, and finally the face of the gorilla.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/08/drawing-gorilla-steps.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>We'll draw the gorilla in multiple steps</em></p>
<h3 id="heading-how-to-draw-the-body-of-the-gorilla">How to draw the body of the gorilla</h3>
<p>We'll draw the body of the gorilla as a path. Paths start with the <code>beginPath</code> method and end with either calling the <code>fill</code> or the <code>stroke</code> method – or both. </p>
<p>In between, we'll build the path by calling path-building methods. In this case, to build up the body of the gorilla we'll use the <code>moveTo</code> and a bunch of <code>lineTo</code> methods.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-12-at-23.53.57.png" alt="Image" width="600" height="400" loading="lazy">
<em>The body of the gorilla. The image shows the path we're filling.</em></p>
<p>We'll set the fill style to black, and then we'll begin a path. Move to a starting position and then draw straight lines to draw the silhouette of the gorilla. Once we're finished, we'll fill the shape with the <code>fill</code> method.</p>
<pre><code class="lang-js">. . .

ctx.fillStyle = <span class="hljs-string">"black"</span>;

<span class="hljs-comment">// Draw the Body of the Gorilla</span>
ctx.beginPath();
ctx.moveTo(<span class="hljs-number">-68</span>, <span class="hljs-number">72</span>);
ctx.lineTo(<span class="hljs-number">-80</span>, <span class="hljs-number">176</span>);

ctx.lineTo(<span class="hljs-number">-44</span>, <span class="hljs-number">308</span>);
ctx.lineTo(<span class="hljs-number">0</span>, <span class="hljs-number">336</span>);
ctx.lineTo(+<span class="hljs-number">44</span>, <span class="hljs-number">308</span>);

ctx.lineTo(+<span class="hljs-number">80</span>, <span class="hljs-number">176</span>);
ctx.lineTo(+<span class="hljs-number">68</span>, <span class="hljs-number">72</span>);
ctx.fill();

. . .
</code></pre>
<p>In case you are wondering how I came up with these coordinates, I actually started with an initial sketch with pen and paper. I tried to estimate the coordinates, tried them with code, and then adjusted them until they started getting the right shape. Of course, you might have other methods as well.</p>
<h3 id="heading-how-to-draw-the-legs-of-the-gorilla">How to draw the legs of the gorilla</h3>
<p>We'll draw the legs the same way. We could even continue the same path we used before, but it might be easier to see what's happening if we break this down into separate paths.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-12-at-23.09.59.png" alt="Image" width="600" height="400" loading="lazy">
<em>Drawing the legs as two separate paths</em></p>
<pre><code class="lang-js">. . .

<span class="hljs-comment">// Draw the Left Leg</span>
ctx.beginPath();
ctx.moveTo(<span class="hljs-number">0</span>, <span class="hljs-number">72</span>);
ctx.lineTo(<span class="hljs-number">-28</span>, <span class="hljs-number">0</span>);
ctx.lineTo(<span class="hljs-number">-80</span>, <span class="hljs-number">0</span>);
ctx.lineTo(<span class="hljs-number">-68</span>, <span class="hljs-number">72</span>);
ctx.fill();

<span class="hljs-comment">// Draw the Right Leg</span>
ctx.beginPath();
ctx.moveTo(<span class="hljs-number">0</span>, <span class="hljs-number">72</span>);
ctx.lineTo(+<span class="hljs-number">28</span>, <span class="hljs-number">0</span>);
ctx.lineTo(+<span class="hljs-number">80</span>, <span class="hljs-number">0</span>);
ctx.lineTo(+<span class="hljs-number">68</span>, <span class="hljs-number">72</span>);
ctx.fill();

. . .
</code></pre>
<p>The fill color in this case is also going to be black. Why? Because that's what we set the <code>fillStyle</code> property to, the last time we set its value. Every path that follows this statement will use this color until we change its value.</p>
<h3 id="heading-how-to-draw-the-arms-of-the-gorilla">How to draw the arms of the gorilla</h3>
<p>While the body and the legs are relatively simple parts of the gorilla, the arms are a bit more complicated. We'll draw them as a curve.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-12-at-23.12.03.png" alt="Image" width="600" height="400" loading="lazy">
<em>Drawing the arms as a curve</em></p>
<p>Let’s start with the left arm. The main part of this is actually only two lines of code. We'll use the <code>moveTo</code> method to move to the shoulder of the gorilla, then from there, we'll draw the arm as a quadratic curve with the <code>quadraticCurveTo</code> method.</p>
<p>A quadratic curve is a simple curve with one control point. As the curve goes from the starting point (which we'll set with <code>moveTo</code>), the curve bends towards this control point (set as the first two arguments of the <code>quadraticCurveTo</code> method) as it reaches its end position (set as the last two arguments).</p>
<pre><code class="lang-js">. . .

ctx.strokeStyle = <span class="hljs-string">"black"</span>;
ctx.lineWidth = <span class="hljs-number">70</span>;

<span class="hljs-comment">// Draw the Left Arm</span>
ctx.beginPath();
ctx.moveTo(<span class="hljs-number">-56</span>, <span class="hljs-number">200</span>);
ctx.quadraticCurveTo(<span class="hljs-number">-176</span>, <span class="hljs-number">180</span>, <span class="hljs-number">-112</span>, <span class="hljs-number">48</span>);
ctx.stroke();

<span class="hljs-comment">// Draw the Right Arm</span>
ctx.beginPath();
ctx.moveTo(+<span class="hljs-number">56</span>, <span class="hljs-number">200</span>);
ctx.quadraticCurveTo(+<span class="hljs-number">176</span>, <span class="hljs-number">180</span>, +<span class="hljs-number">112</span>, <span class="hljs-number">48</span>);
ctx.stroke();

. . .
</code></pre>
<p>We'll draw the hands as strokes. Instead of ending the path with the <code>fill</code> method, we'll use the <code>stroke</code> method.</p>
<p>We'll also set up the styling differently. Instead of using the <code>fillStyle</code> property, here we'll set the color with <code>strokeStyle</code> and give thickness to the arms with the <code>lineWidth</code> property.</p>
<p>Drawing the right arm is the same, except the horizontal coordinates are flipped. The negative numbers have a positive sign now.</p>
<p>As a result, our gorillas should start to gain shape. They still don’t have a face, but we have the whole silhouette now.</p>
<h3 id="heading-how-to-draw-the-face-of-the-gorilla">How to draw the face of the gorilla</h3>
<p>The face of the gorilla comes together from multiple different parts. First, we'll draw the facial mask with three circles.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/08/gorilla-facial-mask.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>We draw the facial mask as three circles</em></p>
<p>Unfortunately, we don’t have a simple fill circle method, as we have in the case of rectangles. We have to draw an <code>arc</code> instead.</p>
<p>An <code>arc</code> method can be called as part of a path. We'll start each circle with the <code>beginPath</code> method and end with the <code>fill</code> method.</p>
<pre><code class="lang-js">. . .

ctx.fillStyle = <span class="hljs-string">"lightgray"</span>;

<span class="hljs-comment">// Draw the Facial Mask</span>
ctx.beginPath();
ctx.arc(<span class="hljs-number">0</span>, <span class="hljs-number">252</span>, <span class="hljs-number">36</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span> * <span class="hljs-built_in">Math</span>.PI);
ctx.fill();

ctx.beginPath();
ctx.arc(<span class="hljs-number">-14</span>, <span class="hljs-number">280</span>, <span class="hljs-number">16</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span> * <span class="hljs-built_in">Math</span>.PI);
ctx.fill();

ctx.beginPath();
ctx.arc(+<span class="hljs-number">14</span>, <span class="hljs-number">280</span>, <span class="hljs-number">16</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span> * <span class="hljs-built_in">Math</span>.PI);
ctx.fill();

. . .
</code></pre>
<p>The <code>arc</code> method has a lot of properties. This might look a bit scary, but we only need to focus on the first 3 when drawing circles:</p>
<ul>
<li>The first two arguments are <code>x</code> and <code>y</code>, the center coordinates of the arc.</li>
<li>The third argument is the <code>radius</code>.</li>
<li>Then the last two arguments are the <code>startAngle</code> and the <code>endAngle</code> of the arc in radians. Because here we want to have a full circle and not an arc, we'll start with 0 and end at a full circle. A full circle in radians is two times Pi.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-12-at-23.17.08.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If these last two properties are confusing, don't worry about it. What's important is that when we draw circles, they are always <code>0</code> and <code>2 * Math.Pi</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/08/gorilla-final-steps.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>We draw the eyes, the nostrils, and the mouth</em></p>
<p>Then we draw the eyes of the gorilla as two other circles. Here the center coordinates of the circles are the same as the bigger gray circles around them. Only their radius and their fill color are different.</p>
<pre><code class="lang-js">. . .

ctx.fillStyle = <span class="hljs-string">"black"</span>;

<span class="hljs-comment">// Draw the Left Eye</span>
ctx.beginPath();
ctx.arc(<span class="hljs-number">-14</span>, <span class="hljs-number">280</span>, <span class="hljs-number">6</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span> * <span class="hljs-built_in">Math</span>.PI);
ctx.fill();

<span class="hljs-comment">// Draw the Right Eye</span>
ctx.beginPath();
ctx.arc(+<span class="hljs-number">14</span>, <span class="hljs-number">280</span>, <span class="hljs-number">6</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span> * <span class="hljs-built_in">Math</span>.PI);
ctx.fill();

. . .
</code></pre>
<p>Then for the nose, we'll draw two short lines as nostrils. They are part of the same path, and we'll call the <code>moveTo</code> method in between to get from one side to the other. Before calling stroke at the end of this path, we'll update the <code>lineWidth</code> property. </p>
<pre><code class="lang-js">. . .

ctx.lineWidth = <span class="hljs-number">6</span>;

<span class="hljs-comment">// Draw the Nostrils</span>
ctx.beginPath();
ctx.moveTo(<span class="hljs-number">-14</span>, <span class="hljs-number">266</span>);
ctx.lineTo(<span class="hljs-number">-6</span>, <span class="hljs-number">260</span>);

ctx.moveTo(<span class="hljs-number">14</span>, <span class="hljs-number">266</span>);
ctx.lineTo(+<span class="hljs-number">6</span>, <span class="hljs-number">260</span>);
ctx.stroke();

. . .
</code></pre>
<p>And finally, we'll also add a path for the mouth. This could be part of the same path as the nose, because it has the same line width and color, but might be clearer to have them separate.</p>
<pre><code class="lang-js">. . .

<span class="hljs-comment">// Draw the Mouth</span>
ctx.beginPath();
ctx.moveTo(<span class="hljs-number">-20</span>, <span class="hljs-number">230</span>);
ctx.quadraticCurveTo(<span class="hljs-number">0</span>, <span class="hljs-number">245</span>, <span class="hljs-number">20</span>, <span class="hljs-number">230</span>);
ctx.stroke();
</code></pre>
<p>Let's draw another quadratic curve. This is similar to the one we used for the arms. The start and endpoint of this curve are on the same level, but the control point is a bit higher so the middle of the mouth is higher than the two sides.</p>
<h2 id="heading-next-steps">Next Steps</h2>
<p>Now that we have a basic gorilla, what can we do with it? We can build a whole game around it. In this <a target="_blank" href="https://www.freecodecamp.org/news/gorillas-game-in-javascript/">JavaScript Game Tutorial</a> we rebuild the 1991 classic game, Gorillas.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-01-19-at-23.49.34.png" alt="Image" width="600" height="400" loading="lazy">
<em>Screenshot from the JavaScript Game Tutorial</em></p>
<p>For a deep dive, read the <a target="_blank" href="https://www.freecodecamp.org/news/gorillas-game-in-javascript/">full tutorial</a> where we build up a complete game with plain JavaScript. In this tutorial, we not only cover how to draw the gorillas and the city skyline but also implement the whole game logic. From event handling, through the animation loop, to hit detection.</p>
<p>For even more, you can also watch the <a target="_blank" href="https://www.youtube.com/watch?v=2q5EufbUEQk">extended tutorial on YouTube</a>. In the YouTube version, we also cover how to make the buildings destructible, how to animate the hand of the gorilla to follow the drag movement while aiming, have nicer graphics, and we add AI logic, so you can play against the computer.</p>
<p>Check it out to learn more:</p>
<p><a target="_blank" href="https://www.youtube.com/embed/2q5EufbUEQk?feature=oembed">Embedded content</a></p>
<p>You can subscribe to my channel for more JavaScript game development tutorials:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/undefined" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to lock an angle when drawing on canvas in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ By Thang Minh Vu In many drawing tools (Adobe Photoshop, Sketch, and so on), if we hold the SHIFT button when drawing a line, we can create perfectly straight lines horizontally or vertically. Recently, I tried implementing this feature in canvas by ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-lock-an-angle-when-drawing-on-canvas-in-javascript-51938b5abc7c/</link>
                <guid isPermaLink="false">66c35328d58e4fdd567d51ae</guid>
                
                    <category>
                        <![CDATA[ canvas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ geometry ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 18 Mar 2019 16:16:31 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*cWcey5rf6AkuNtkVZ7ywwg.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Thang Minh Vu</p>
<p>In many drawing tools (<a target="_blank" href="https://www.adobe.com/products/photoshop.html">Adobe Photoshop</a>, <a target="_blank" href="https://www.sketchapp.com/">Sketch</a>, and so on), if we hold the SHIFT button when drawing a line, we can create perfectly straight lines horizontally or vertically.</p>
<p>Recently, I tried implementing this feature in canvas by JavaScript. The process is really interesting. I would like to share the progress of how I approach it.</p>
<p><strong>Demo</strong>: To easier understand the idea, you can check a demo version at the <a target="_blank" href="https://ittus.github.io/draw-lock-angle/">demo page</a>.</p>
<h3 id="heading-requirements">Requirements</h3>
<p><strong>Input</strong></p>
<ul>
<li>A base point (B)</li>
<li>Current mouse position (M)</li>
</ul>
<p><strong>Output</strong></p>
<ul>
<li>Projection of current mouse position on x-axis or y-axis (P)</li>
</ul>
<p>For convenience, in all graphs, we will mark the base point by a red circle and the current mouse point by a green circle.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/zvt4t9MmiO6Uxc3zAyLDxUOta3S-j4Nl7JvE" alt="Image" width="488" height="458" loading="lazy">
<em>Problem: Decide which projection is better</em></p>
<h3 id="heading-simple-solution">Simple solution</h3>
<p>As I tackle the problem, it’s intuitive to see we can calculate the distance between the current mouse position with the horizontal line and vertical line. If the mouse position is nearer the horizontal line than the vertical line, we will take the projection on the horizontal line, and vice versa.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/F-mQyWvLknInihDnYTgeS2CYyiHljKRB-P1R" alt="Image" width="632" height="495" loading="lazy"></p>
<p>The calculation is quite simple — here is the Javascript code:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/AmQiLZ6chh1YF30QhI6MXs0Qrpwq1SkXAdti" alt="Image" width="800" height="475" loading="lazy"></p>
<h3 id="heading-extended-problem">Extended Problem</h3>
<p>How about if we want to project on the bisector line between the horizontal line and vertical line (similar with <a target="_blank" href="https://www.sketchapp.com/">Sketch</a>)? That means users can project the mouse position on the horizontal line, vertical line, 45-degree angle line, or 135-degree angle line.</p>
<p>The approach is similar. This time we need to calculate the distance between the mouse position to 4 lines: horizontal line, vertical line, and 2 bisector lines (45-degree line and 135-degree line). But the calculation is more complex.</p>
<p>We still can divide it into 2 steps:</p>
<ol>
<li>Determine which line is nearest with mouse position</li>
<li>Calculate the projection of mouse position on the nearest line</li>
</ol>
<p><img src="https://cdn-media-1.freecodecamp.org/images/yRRlpXpZg16PFuGjohkEwMBRTQ074yN4UmvH" alt="Image" width="489" height="460" loading="lazy"></p>
<h4 id="heading-step-1-determine-which-line-is-nearest-with-mouse-position">Step 1: Determine which line is nearest with mouse position</h4>
<p>First, we need to determine line formulation of 4 lines above. Because we already know the base point (x0, y0) and the line angle, it’s easy to figure out the formulation of each line.</p>
<blockquote>
<p>Example: To calculate the formula of the 45-degree bisector, we already know that the line will go through the base point (x0, y0) and (x0 + 1, y0 + 1). Using the <a target="_blank" href="https://www.wikihow.com/Find-the-Equation-of-a-Line">Find-the-Equation-of-a-Line</a> method, we can figure out the line formula.</p>
</blockquote>
<p>Finally, we will have 4 lines’ formulas:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ngaxjDK6zWtgP74BOXPwMU2jZY014c7L-lu6" alt="Image" width="187" height="82" loading="lazy"></p>
<p>To calculate the distance between the base mouse position to each line, we can use a popular math formula:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/C4Tk7kqRbwGbPtYFwK-HDSRlmVnGTRunxAso" alt="Image" width="359" height="27" loading="lazy">
<em>Distance from a point to a line</em></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Adk5BQAv15Jy4IuGUBSyKiSxkU68gEgsdh7z" alt="Image" width="800" height="561" loading="lazy">
<em>Finding the nearest line</em></p>
<h4 id="heading-step-2-calculate-the-orthogonal-projection-of-mouse-position-on-the-nearest-line">Step 2: Calculate the orthogonal projection of mouse position on the nearest line</h4>
<p>Now the problem becomes calculating the orthogonal projection of the mouse position (M) to the nearest line with the formula: ax + by + c = 0 (L)</p>
<p>There are multiple ways to solve this problem. I took a simple way: First, calculate the formula of the line which contains mouse position M and perpendicular to line L, called L'. Then, solve the system of equations to get the intersection point between line L and L', which is the projection point which we are finding.</p>
<p>After some calculation, I figured out the formula of L’, which goes through M (x0, y0) and perpendicular to L (ax + by + c = 0):</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/BwlHT2VPl2baMMHQtQYI2vGkCUq0jl0ZpiLz" alt="Image" width="198" height="17" loading="lazy"></p>
<p>Now to find the intersection, we need to solve the system of equations:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/4nJ1rFj7FrXEwZ0KK3MLEGo10DMJDUrchUxB" alt="Image" width="211" height="54" loading="lazy"></p>
<p>Using <a target="_blank" href="https://en.wikipedia.org/wiki/Cramer%27s_rule">Cramer’s rule</a> and matrix determinant, we can solve this equation easily:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/YeHWX9l70xghLPvDkqTZA19RSbRGyRIZq4WJ" alt="Image" width="800" height="526" loading="lazy">
<em>Solve simultaneous equations</em></p>
<h3 id="heading-boundary">Boundary</h3>
<p>There is a situation when we want to limit the boundary of projection.</p>
<p>Example:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/3WNRAcorUIwF9lwihmXCjAna8DovCrhgmUxi" alt="Image" width="379" height="404" loading="lazy">
<em>The projection point is outside of the boundary</em></p>
<p>In this case, we want to limit the projection in the white rectangle area, but using the discussed method, the projection point can be outside of the boundary area.</p>
<p>In this situation, we can simply get the intersection point of line L’ to the boundary (called P’).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Zl5D-QVbgmra2XCyD6khtLSFE1sF9VzPz49c" alt="Image" width="800" height="1049" loading="lazy">
<em>Support boundary of the projection</em></p>
<h3 id="heading-full-source-code"><strong>Full source code</strong></h3>
<p>You can check out the demo and source code on <a target="_blank" href="https://github.com/ittus/draw-lock-angle">Github</a>.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
