Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9272277
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T15:50:07+00:00 2026-06-18T15:50:07+00:00

So I’m new to Html/Javascript. So I decided to play around with the canvas

  • 0

So I’m new to Html/Javascript. So I decided to play around with the canvas and display tiles and get mouse clicks. What I’m trying to do is get the mouse click, and turn the tile that the user clicked on to be changed colors. The problem is the way I’m getting where the user clicked to be converted onto tile coordinates. It seems that the farther down right I go the less accurate it gets too.

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Fun Canvas!!!</title>
    <style>
        canvas 
        {
            position: relative;
            padding-left: 0;
            padding-right: 0;
            margin-left: auto;
            margin-right: auto;
            display: block;
            border:1px solid #000000;
            height: 100%;
            width: 100%;
        }
    </style>
    <script>
        // Map Related
        var m_iTotalWidth;
        var m_iTotalHeight;
        var m_iMapWidth = 60;
        var m_iMapHeight = 30;
        var m_iTileWidth;
        var m_iTileHeight;
        var m_bColorFull = new Array(m_iMapWidth);
        var m_cColors = ['#FF0000', '#FF7700', '#FFFF00', '#00FF00', '#1500FF', '#C700FF'];
        var m_cDefaultColor = "#000";
        var m_CanvaContext;
        var m_Canvas;
        var m_iBorderLength = 1;

        // Map Color related
        var iMin = 0;
        var iMax = 255;
        var m_iPrevX = 0;
        var m_iPrevY = 0;

        // GameSpeed
        var m_iGameSpeed = 60;

        var m_IntervalID;
        document.addEventListener("DOMContentLoaded", initialize, false);
        document.documentElement.style.overflowX = 'hidden';     // horizontal scrollbar will be hidden
        document.documentElement.style.overflowY = 'hidden';

        function initialize() {
            m_IntervalID = window.setInterval("gameLoop();", m_iGameSpeed);

            // Get canvas context for drawing
            m_CanvasContext = document.getElementById("myCanvas").getContext("2d");
            setCanvasSize();
            m_Canvas = document.getElementById("myCanvas");
            document.addEventListener('mousedown', getPosition, false);

            for (var x = 0; x < m_iMapWidth; x++) {
                m_bColorFull[x] = new Array(m_iMapHeight);

                for (var y = 0; y < m_iMapHeight; y++)
                {
                    if (y == 0)
                        paintTile(x, y, "white", 2);

                    m_bColorFull[x][y] = false;
                }
            }

            drawMap();
            gameLoop();
        }

        // Runs all the functions required for the game to work.
        function gameLoop() {
            drawMap();
        }

        // Draws everything on the canvas.
        function drawMap() {

            for (var x = 0; x < m_iMapWidth; x++)
                for (var y = 1; y < m_iMapHeight; y++) {

                    if (m_bColorFull[x][y])
                        paintTile(x, y, getRandomColor(0, 255), 2);

                    else
                        paintTile(x, y, m_cDefaultColor, 2);
                }
        }

        // Paints a tile on the screen, handles converting pixel to tile.
        function paintTile(x, y, color, borderThickness) 
        {
            m_CanvasContext.fillStyle = color;
            m_CanvasContext.fillRect((x * m_iTileWidth) + borderThickness, (y * m_iTileHeight) + borderThickness, m_iTileWidth - (borderThickness * 2), m_iTileHeight - (borderThickness * 2));
        }

        // Handles clicks.
        function getPosition(event)
        {
            var rect = m_Canvas.getBoundingClientRect();
            var x = event.clientX - rect.left;
            var y = event.clientY - rect.top;
            x = Math.round(x / m_iTileWidth);
            y = Math.round(y / m_iTileHeight);

            for (var xIndex = 0; xIndex < m_iMapWidth; xIndex++)
                for (var yIndex = 0; yIndex < 1; yIndex++)
                    paintTile(xIndex, yIndex, "white", 0);

            writeMessage(1, "black", x + "-" + y);
            m_bColorFull[x][y] = !m_bColorFull[x][y];
        }

        // Sets the canvas as big as the broswer size.
        function setCanvasSize()
        {
            m_CanvasContext.scale(1, 1);
            m_iTileWidth = Math.floor(m_CanvasContext.canvas.width / m_iMapWidth);//Math.floor(window.innerWidth / m_iMapWidth);
            m_iTileHeight = Math.floor(m_CanvasContext.canvas.height / m_iMapHeight); //Math.floor(window.innerHeight / m_iMapHeight);
            //m_CanvasContext.canvas.width = (m_iTileWidth * m_iMapWidth);
            //m_CanvasContext.canvas.height = (m_iTileHeight * m_iMapHeight);
        }

        function writeMessage(startTile, color, message) 
        {
            m_CanvasContext.font = '16pt Calibri';
            m_CanvasContext.fillStyle = color;
            m_CanvasContext.fillText(message, startTile * m_iTileWidth, 16);
        }
        /*********************************************************************************************************/
        /*USEFULL FUNCTIONS*/

        function getRandomColor(iMin, iMax) {

            //return m_cColors[getRandomNumber(0, m_cColors.length)];
            // creating a random number between iMin and iMax
            var r = getRandomNumber(iMin, iMax)
            var g = getRandomNumber(iMin, iMax)
            var b = getRandomNumber(iMin, iMax)

            // going from decimal to hex
            var hexR = r.toString(16);
            var hexG = g.toString(16);
            var hexB = b.toString(16);

            // making sure single character values are prepended with a "0"
            if (hexR.length == 1)
                hexR = "0" + hexR;

            if (hexG.length == 1)
                hexG = "0" + hexG;

            if (hexB.length == 1)
                hexB = "0" + hexB;

            // creating the hex value by concatenatening the string values
            var hexColor = "#" + hexR + hexG + hexB;
            return hexColor.toUpperCase();
        }

        function getRandomNumber(iMin, iMax) {
            return Math.floor((Math.random() * (iMax - iMin)) + iMin);
        }
    </script>
</head>
<body>
    <canvas id="myCanvas" width="1000" height="500" style="border:1px solid #000000;">
</canvas>
</body>
</html>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T15:50:08+00:00Added an answer on June 18, 2026 at 3:50 pm

    I’ve did this already: http://jsfiddle.net/Saturnix/rJD3r/

    and explained in detail here: https://ijosephblog.wordpress.com/2012/05/09/implementing-conways-game-of-life-in-html5-canvas-with-javascript/

    There’s much more stuff to what you really need, so here I’ve made a simpler version: http://jsfiddle.net/DTMRt/

    This chunk of code from the demo above converts mouse coordinates into an array index.

    var j = Math.floor((g.mouseX / (dim + spacing)));
    var i = Math.floor(g.mouseY / (dim + spacing));
    grid[j][i] = "mouse is passing over here!";
    

    where dim is the dimension of a tile, spacing is the distance between the tiles (you can set that to zero) and g.mouseX/g.mouseY are the mouse coordinates.

    You need all your tiles to be in an array of arrays, I did it like this:

    var grid = new Array(grid_width);
    
    for (var j = 0; j<grid_width; j++){
    grid[j] = new Array(grid_height);
    };
    

    where grid_width and grid_height will be number of rows and columns of tiles.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to render a haml file in a javascript response like so:
I want use html5's new tag to play a wav file (currently only supported
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
Is it possible to replace javascript w/ HTML if JavaScript is not enabled on
I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
I have a small JavaScript validation script that validates inputs based on Regex. I
I have this code to decode numeric html entities to the UTF8 equivalent character.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.