
    
        
        
        
                
        
        
        
                
        
        
        
            
{"version":"https:\/\/jsonfeed.org\/version\/1","title":"mathspp.com feed","home_page_url":"https:\/\/mathspp.com\/blog\/tags\/javascript","feed_url":"https:\/\/mathspp.com\/blog\/tags\/javascript.json","description":"Stay up-to-date with the articles on mathematics and programming that get published to mathspp.com.","author":{"name":"Rodrigo Gir\u00e3o Serr\u00e3o"},"items":[{"title":"TIL #120 \u2013 Circle vs rectangle collision detection","date_published":"2025-03-06T23:45:00+01:00","id":"https:\/\/mathspp.com\/blog\/til\/circle-vs-rectangle-collision-detection","url":"https:\/\/mathspp.com\/blog\/til\/circle-vs-rectangle-collision-detection","content_html":"<p>Today I learned how to detect collisions between circles and rectangles with 100% accuracy.<\/p>\n\n<h2 id=\"circle-vs-rectangle-collision-detection\">Circle vs rectangle collision detection<a href=\"#circle-vs-rectangle-collision-detection\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>In a <a href=\"\/blog\/javascript-2d-scrolling-game-tutorial\">JavaScript tutorial I published recently<\/a>, the game that I presented included some very basic collision detection between a circle and a rectangle, and it used the circle's bounding box.\nThis meant that the collision detection sucked if the circle was close to the corners of the rectangle.<\/p>\n<p>Today I sat down to think about it for a second and figured out how to implement pixel-perfect collision detection between a rectangle and a circle, as the demo below demonstrates:<\/p>\n<canvas id=\"mainCanvas1\" style=\"background:var(--ui); margin: auto; display: block;\"><\/canvas><script>\n    const canvas1 = document.getElementById(\"mainCanvas1\");\n    const ctx1 = canvas1.getContext(\"2d\");\n\n    const WIDTH = Math.min(600, 0.95 * document.documentElement.clientWidth);\n    const HEIGHT = 400;\n    canvas1.width = WIDTH;\n    canvas1.height = HEIGHT;\n\n    var style = window.getComputedStyle(document.body);\n    const RED = style.getPropertyValue(\"--re\");\n    const GREEN = style.getPropertyValue(\"--gr\");\n    const CIRCLE_COLOUR = style.getPropertyValue(\"--tx\");\n\n    const radius = 25;\n\n    function draw1(evt) {\n        ctx1.clearRect(0, 0, canvas1.width, canvas1.height);\n\n        \/\/ Get mouse position.\n        var rect = canvas1.getBoundingClientRect();\n        var x = evt.clientX - rect.left;\n        var y = evt.clientY - rect.top;\n\n        \/\/ Draw the rectangle.\n        ctx1.fillStyle = collision1(x, y) ? RED : GREEN;\n        ctx1.fillRect(WIDTH \/ 4, HEIGHT \/ 4, WIDTH \/ 2, HEIGHT \/ 2);\n\n        \/\/ Draw the circle.\n        ctx1.fillStyle = CIRCLE_COLOUR;\n        ctx1.beginPath();\n        ctx1.arc(x, y, radius, 0, 2 * Math.PI);\n        ctx1.fill();\n    }\n\n    function collision1(x, y) {\n        var left = WIDTH \/ 4, right = 3 * WIDTH \/ 4;\n        var top = HEIGHT \/ 4, bottom = 3 * HEIGHT \/ 4;\n        var corners = [\n            { x: left, y: top },\n            { x: right, y: top },\n            { x: left, y: bottom },\n            { x: right, y: bottom },\n        ];\n        for (var c of corners) {\n            if ((c.x - x) ** 2 + (c.y - y) ** 2 <= radius ** 2) {\n                return true;\n            }\n        }\n        return (x >= left - radius && x <= right + radius && y >= top && y <= bottom) || (x >= left && x <= right && y >= top - radius && y <= bottom + radius);\n    }\n\n    document.addEventListener(\n        \"mousemove\",\n        draw1,\n    );\n<\/script><p>The first thing I implemented was pixel-perfect collision detection with the <em>corners<\/em> of the rectangle.\nThis is easy to check because each corner is a single point and to check if a single point is inside a circle amounts to checking if the distance between the point and the centre of the circle is less than the radius of the circle:<\/p>\n<p class=\"mathjax mathjax--block\">\\[\n(p_x - c_x)^2 + (p_y - c_y)^2 \\leq r^2\\ ?\\]<\/p>\n<p>In the demo below, try getting the circle close to the corners of the rectangle: that's when a collision is detected.<\/p>\n<canvas id=\"mainCanvas2\" style=\"background:var(--ui); margin: auto; display: block;\"><\/canvas><script>\n    const canvas2 = document.getElementById(\"mainCanvas2\");\n    const ctx2 = canvas2.getContext(\"2d\");\n\n    canvas2.width = WIDTH;\n    canvas2.height = HEIGHT;\n\n    function draw2(evt) {\n        ctx2.clearRect(0, 0, canvas2.width, canvas2.height);\n\n        \/\/ Get mouse position.\n        var rect = canvas2.getBoundingClientRect();\n        var x = evt.clientX - rect.left;\n        var y = evt.clientY - rect.top;\n\n        \/\/ Draw the rectangle.\n        ctx2.fillStyle = collision2(x, y) ? RED : GREEN;\n        ctx2.fillRect(WIDTH \/ 4, HEIGHT \/ 4, WIDTH \/ 2, HEIGHT...<\/script>","summary":"Today I learned how to detect collisions between circles and rectangles with 100% accuracy.","date_modified":"2025-10-20T22:34:56+02:00","tags":["geometry","javascript","programming"],"image":"\/user\/pages\/02.blog\/04.til\/120.circle-vs-rectangle-collision-detection\/thumbnail.webp"},{"title":"JavaScript 2D scrolling game tutorial","date_published":"2025-02-28T12:08:00+01:00","id":"https:\/\/mathspp.com\/blog\/javascript-2d-scrolling-game-tutorial","url":"https:\/\/mathspp.com\/blog\/javascript-2d-scrolling-game-tutorial","content_html":"<p>This tutorial walks you through implementing a 2D scrolling game in JavaScript.<\/p>\n\n<p>This JavaScript tutorial is for people who know programming (for example, in Python) but have no JavaScript knowledge.\nIn this tutorial we will build a 2D scrolling game where the player (a red ball) will jump to avoid obstacles (black rectangles) that come toward the player at increasing speeds.<\/p>\n<p>You can play a demo of the game below.\nClick the gray rectangle to start the game and press <kbd>SPACE<\/kbd> to make the player jump over obstacles.\n(If you click the game area again, it restarts.)<\/p>\n<iframe style=\"border: 0;\" width=\"100%\" height=\"330\" src=\"\/blog\/javascript-2d-scrolling-game-tutorial\/game21.html\"><\/iframe>\n<h2 id=\"javascript-and-the-web\">JavaScript and the web<a href=\"#javascript-and-the-web\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>JavaScript is a language that runs directly in your browser without you having to do anything else.\nIn fact, if you click the address bar (where you usually type the URL addresses of the websites you want to visit) and type something like <code>javascript:alert(\"Hello, world!\");<\/code>, the browser should display a pop-up with the message &ldquo;Hello, world!&rdquo;.<\/p>\n<p>JavaScript is tightly integrated with your browser.\nThis means you can also use JavaScript to manipulate web pages.\nIn JavaScript, <code>document<\/code> is a variable that refers to the web page (document) you're currently on, and it lets you interact with the page programmatically.\nHere's a fun example:<\/p>\n<ol><li>open the Wikipedia page at <wikipedia.org>; and<\/wikipedia.org><\/li>\n<li>type <code>javascript:document.getElementById(\"www-wikipedia-org\").remove()<\/code> in your address bar.<\/li>\n<\/ol><p>If all goes well[^1] and you copy that code correctly, it should look like the page disappeared.\nIn fact, if you look at the end of the code you pasted, there's a <code>remove<\/code> in there.\nWhat we did was ask the web page for an element with the unique ID <code>www-wikipedia-org<\/code>, which for the main Wikipedia page refers to the whole visible page.<\/p>\n<p>Don't worry, you didn't hack Wikipedia and you aren't going to jail.\nIf you refresh the page, you should get a brand new copy of the page you were at, and everything should be back to normal.\nThat's because the JavaScript code you ran when you pasted it in the address bar was running <em>locally<\/em>, on your browser, on your copy of the Wikipedia main page.\nIt ran on the &ldquo;client side&rdquo;.<\/p>\n<h2 id=\"developer-console\">Developer console<a href=\"#developer-console\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>Next, I want to tell you about the developer console.\nThe developer console is like a debugger, but instead of being built into your IDE of choice, it's built into your web browser.\nAll major web browsers have a developer console: Safari, Chrome, Firefox, Opera, Brave, etc.<\/p>\n<p>Each browser has a different shortcut to open the developer console, so you may want to look up &ldquo;Open developer console INSERT_BROWSER_HERE&rdquo;.<\/p>\n<p>In most browsers, a roundabout way of achieving this effect is right-clicking <em>anywhere<\/em> on a page and then looking for the option that says something like &ldquo;Inspect&rdquo; or &ldquo;Inspect element&rdquo;.\nThat should open a window that lets you peek at the source code of the page you're currently on, and it should have a tab that says something like &ldquo;Console&rdquo; or &ldquo;JavaScript console&rdquo;.<\/p>\n<p>If you haven't been able to open the console yet, look...<\/p>","summary":"This tutorial walks you through implementing a 2D scrolling game in JavaScript.","date_modified":"2025-12-19T21:10:22+01:00","tags":["game","javascript","programming"],"image":"\/user\/pages\/02.blog\/javascript-2d-scrolling-game-tutorial\/thumbnail.webp"},{"title":"TIL #045 \u2013 using JavaScript functions in PyScript","date_published":"2022-05-01T00:00:00+02:00","id":"https:\/\/mathspp.com\/blog\/til\/045","url":"https:\/\/mathspp.com\/blog\/til\/045","content_html":"<p>Today I learned how to use JavaScript functions in PyScript.<\/p>\n\n<script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n<script defer src=\"\/user\/themes\/myquark\/js\/pyscript_alpha.min.js\"><\/script>\n<py-script>\nimport datetime\n\nfrom js import setInterval\nfrom pyodide import to_js\n\ndef update_timestamp(elem):\n    elem.write(\n        format(datetime.datetime.now(), \"%H:%M:%S, %A, %d %B %Y\")\n    )\n\nelem = Element(\"timestamp_updater\")\n_ = setInterval(\n    to_js(lambda: update_timestamp(elem)),\n    1000  # Update every 1000 ms\n)\n<\/py-script>\n<h2 id=\"what-is-pyscript\">What is PyScript?<a href=\"#what-is-pyscript\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>In case you missed, yesterday I learned about <a href=\"\/blog\/til\/pyscript\">PyScript<\/a>,\na tool that allows you to use Python inside your HTML!\nIn other words, PyScript enables you to run Python on the client side.<\/p>\n<h2 id=\"how-to-use-javascript-functions-in-pyscript\">How to use JavaScript functions in PyScript?<a href=\"#how-to-use-javascript-functions-in-pyscript\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>In order to use JavaScript functions in PyScript, you can import them from the available <code>js<\/code> module.\nFor example, to use <code>console.log<\/code> from within PyScript, you just type <code>from js import console<\/code> in your PyScript tag.\nThen, you can call <code>console.log<\/code> regularly:<\/p>\n<pre><code class=\"language-html\">&lt;py-script&gt;\nfrom js import console\n\nconsole.log(\"Hey there, from 'console.log' inside PyScript!\")\n&lt;\/py-script&gt;<\/code><\/pre>\n<p>If you include that in one of your pages and then check the console,\nyou will find the message <code>Hey there, from 'console.log' inside PyScript!<\/code> in there.<\/p>\n<p>Let me show another example that is slightly more involved.<\/p>\n<h2 id=\"running-a-python-function-periodically-with-setinterval\">Running a Python function periodically with <code>setInterval<\/code><a href=\"#running-a-python-function-periodically-with-setinterval\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>JavaScript has a function <code>setInterval<\/code> that lets you run a function periodically.\nIf we write <code>from js import setInterval<\/code>, that function becomes available to us.\nThat is what is being used to update the timestamp in the next paragraph.<\/p>\n<div class=\"notices blue\">\n<p>It is now <span id=\"timestamp_updater\"><\/span>.<\/p>\n<\/div>\n<p>(If the paragraph above doesn't contain a timestamp that updates every second,\nsomething is broken!\nRight now, PyScript is in alpha, so that might be it...\nBut it may be my fault as well \ud83d\ude43)<\/p>\n<p>What code did I use to get that to run?\nNot much!\nIn this blog post, I just had to link to the PyScript JavaScript file,\nand then I added the following HTML\/Python code:<\/p>\n<pre><code class=\"language-html\">&lt;py-script&gt;\nimport datetime\n\nfrom js import setInterval\nfrom pyodide import to_js\n\ndef update_timestamp(elem):\n    elem.write(\n        format(datetime.datetime.now(), \"%H:%M:%S, %A, %d %B %Y\")\n    )\n\nelem = Element(\"timestamp_updater\")\n_ = setInterval(\n    to_js(lambda: update_timestamp(elem)),\n    1000  # Update every 1000 ms\n)\n&lt;\/py-script&gt;<\/code><\/pre>\n<p>Pretty cool, right?<\/p>\n<p>I learned this by reading a thread that was published on Twitter:<\/p>\n<blockquote class=\"twitter-tweet\"><p lang=\"en\" dir=\"ltr\">Going to be tweeting the session on <a href=\"https:\/\/twitter.com\/pyodide?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">@pyodide<\/a> now. This is the app on top of which PyScript is built. Speakers are Hood Chatham and <a href=\"https:\/\/twitter.com\/RomanYurchak?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">@RomanYurchak<\/a> <a href=\"https:\/\/twitter.com\/hashtag\/PyConUS2022?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">#PyConUS2022<\/a><\/p>\u2014 Playful Python (@playfulpython) <a href=\"https:\/\/twitter.com\/playfulpython\/status\/1520763819152519168?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">May 1, 2022<\/a><\/blockquote>\n<p>That's it for now! <a href=\"\/subscribe\">Stay tuned<\/a> and I'll see you around!<\/p>","summary":"Today I learned how to use JavaScript functions in PyScript.","date_modified":"2025-07-23T16:49:02+02:00","tags":["javascript","programming","python","web development"],"image":"\/user\/pages\/02.blog\/04.til\/045.using-javascript-functions-in-pyscript\/thumbnail.webp"}]}
