Artistic Canvas: Selected Image

I am trying to determine if the user has clicked on an image drawn in a canvas element. Despite clicking on the image, nothing seems to be happening. The alert function is not being triggered and the last condition in the code never evaluates to true. Any suggestions?

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <div id="wrapper">
            <canvas id="game" height="500" width="700">
            </canvas>
        </div>
        <script>
        (function() {
            var canvas = document.getElementById('game'),
                context = canvas.getContext('2d'),
                fps = 1,
                character = Image(),
                positions = [[125, 55], [480, 55], [125, 185], [480, 182], [125, 315], [480, 315]],
                random, x, y, xc, yc = null;

            canvas.addEventListener('click', function(event) {
                xc = event.screenX - canvas.offsetLeft;
                yc = event.screenY - canvas.offsetTop;

                if((xc >= x) && (xc <= (x + character.width)) && (yc >= y) && (yc <= (y + character.height))) {
                    alert('X = ' + x + 'Y = ' + y);
                }
            }, true);

            character.src = 'character.png';

            setInterval(function() {
                random = (Math.floor(Math.random() * 6));

                random = positions[random];
                x = random[0];
                y = random[1];

                context.clearRect(0, 0, canvas.width, canvas.height);
                context.drawImage(character, x, y);
            }, 1000 / fps);
        }());
        </script>
    </body>
</html>

Answer №1

There are a couple of issues that need to be addressed in your code.

Firstly, there is an error in your event code. The screenX function returns the mouse position relative to the screen, but you should be using clientX or pageX for Internet Explorer. Check out the quirksmode website for more information.

canvas.addEventListener('click', function(event) {
    event = event || window.event; // IE doesn't always pass the event param!

    var xc = (event.clientX ? event.clientX : pageX) - canvas.offsetLeft;
    var yc = (event.clientY ? event.clientY : pageY) - canvas.offsetTop;

Secondly, your code won't work in Chrome because of a type error on line 15. You need to use the new keyword when creating the image object to ensure that it returns a new instance.

...
context = canvas.getContext('2d'),
fps = 1,
character = new Image(),
...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating CSS stylesheets dynamically when onchange event occurs

I am currently able to dynamically change style rules using JS, but I feel that this is limiting. I would prefer to be able to swap entire CSS stylesheet files easily. Do you have any suggestions on how to accomplish this? Here is my code: <label>T ...

Adjusting the dimensions of the cropper for optimal image cropping

I am currently working on integrating an image cropper component into my project, using the react-cropper package. However, I am facing a challenge in defining a fixed width and height for the cropper box such as "width:200px; height:300px;" impo ...

Creating a CSS Box Along the Border of Another Box: A Step-by-Step Guide

Is there a way to render a box on another box's border, similar to the example image here: Expected Output I attempted using flexbox to achieve this, but unfortunately wasn't successful in finding a solution. If you have any advice or suggestio ...

What is the purpose of applying the two unique class names (root and disabled) to the DOM in order for it to function correctly?

When it comes to customizing components using material-ui, the process can be a bit tricky. Here's how you can do it: const styles = { root: { '&$disabled': { color: 'white', }, }, disabled: {}, // This is i ...

Trigger a function when <a> is clicked, which will then increment the count by one and reflect this change in the database

The database generates the content of this div ordered by a count number called "cts". Whenever I click on the div, I want the "cts" number to increase by one, and then update the change in the database. This will result in the content changing accordingly ...

Initiate an "execute.document" command directly from the address bar

While reviewing my old website, I stumbled upon this snippet: <input type="image" id="QuickPass" name="QuickPass" src="/images/QuickPass.gif" alt="Quick Pass" onclick="document.pressed=this.value" value="QuickPass" /> nestled within this form: & ...

Is there a way to remove background-color for a:focus?

When working with Twitter Bootstrap, I encountered a challenge. The background-color properties set for navigation items on the :focus state were causing an issue for a specific navigation element that needed have its own styling. Imagine a scenario where ...

PhoneGap fails to fire the ondeviceready event within 5 seconds

Currently, I am in the process of debugging my PhoneGap app using Weinre and facing some persistent errors... The 'deviceready' event has not fired even after 5 seconds. Channels are not firing: onPluginsReady, onCordovaReady, onCordovaConnecti ...

ERROR: Module 'jquery' not found in path 'C:....' when using Gulp and Browserify

Encountering an error: Error: Module 'jquery' not found in path 'F:...\newstyle\assets\lib\helper\html\img\js' at C:\Users...\AppData\Roaming\npm\node_modules&bs ...

`.svg file appearing slightly fuzzy when magnified in Chrome``

After careful consideration, I've chosen to use an SVG for my website logo. However, I am facing an issue with it rendering properly in Google Chrome. When the zoom level is set at 100%, the image appears blurry, but if I zoom out a couple of times, i ...

Utilizing JavaScript/jQuery to activate a Bootstrap navbar post-page load

Having trouble triggering Bootstrap's navbar with plain JavaScript/jQuery while using Bootstrap 3.3.6 and jQuery 1.11.3. The data structure provided for my application cannot be modified in terms of adding classes or ids. <ul> <li ...

Leveraging Three.js Raycaster for a seamless PDF download functionality

Is there a way to trigger a PDF download when clicking on a 3D object in a Three.js scene? Below is an example of how I have set up the Raycaster: var raycaster; var mouse = { x: 0, y: 0 }; init(); function init() { raycaster = new THREE.Raycaster() ...

I am trying to set up an AJAX call in my index.html to connect to a React endpoint, but instead of accessing the intended page, I am getting

I am attempting to execute an AJAX call in my static file index.html to a React endpoint, but instead of the desired response, I am seeing the React homepage. Here is the code snippet from my index.html: <div id="data"></div> <scr ...

What is the best way to include numerous attributes to an element using JavaScript?

Attributes can be included within a string in the following format: let attr = ' min="0" step="5" max="100" '; or let attr = ' min="2019-12-25T19:30" '; and so on. Is there a function available ...

Input the variant number TypeScript as the key value pair

I'm struggling to input an abi key "5777" in Typescript. When I receive a network ID and try to set it in the networks key, the linter displays an error. My issue is that I need to specify "networkId" and it's not always a fixed value like "5777 ...

The computer system encountered an issue in computing the values of the text

Possible Duplicate: Unable to get textfield value using jQuery My current project involves updating input fields based on user changes in quantity for items. Each item is retrieved from a database and I am generating invoices for customers. However, ...

The footer at the bottom of the page is currently malfunctioning

I was able to create an always on the bottom footer using code from Codepen. Here is the HTML: <div class="content"> <header> <p>blabla</p> </header> <main> <p>blaBlabla blub</p ...

Determine the number of network requests being made on a webpage

In my quest to develop a universal method using selenium, I am seeking a way to ensure that all background network activities, including Ajax, Angular, and API calls, have completed. While I am aware of the option to determine the number of active Ajax cal ...

Get the ID from a row that was created dynamically

I have a webpage that pulls information from my database and displays it. Users should be able to click on the "details" link to see more details about a particular record, or click on an input box in the "check" column and submit to update the record stat ...

Leveraging event listeners in conjunction with React's useEffect function

Check out the code example on Code Sandbox here Hey there, I'm trying to implement a feature where clicking a button inside a container displays a box. I've set up an event listener so that when you move your mouse outside the container, the box ...