2

well right now im trying to learn how to use the canvas tag on html, and im having trouble handling mouse events when i apply css to the document.

the issue starts when i move the div containing the canvas and center it on the page, the first poing of the canvas wouldnt be 0 because its centered and for some reason 0,0 would be the beginning of the screen and not the beginning of the canvas, which i found weird because im adding the event listener to the canvas directly.

here is the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>

<style type="text/css">
body {
    font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif;
    background: #42413C;
    margin: 0;
    padding: 0;
    color: #000;
}
#divId {
    width: 800px;
    height: 600px;
    text-align:center;
    margin: 20px auto;
    background-color:#0099FF;
}
</style>

<script>
window.onload = function () {

    var canvas = document.getElementById('canvasId');   
    var c = canvas.getContext('2d');
    alert("lol");
    canvas.addEventListener('mousedown', hmd, false);

    function hmd(e) {
        alert ("x: " + e.clientX + "     y: " + e.clientY); 
    }

}
</script>
</head>

<body>

<div id="divId">

<canvas height="300" width="800" id="canvasId" />

</div>

</body>
</html>

so i read somewhere that the issue was caused by the div, but when i tried to give css directly to the canvas tag it didnt work, so basically what i need to do, is to get that canvas centered or placed anywhere on the screen, but having its first pixel as 0,0. adding a solution would be hard because its centering automatically, so i would need to know the user resolution to be able to calculate the offset so what im looking for is a way to do it simply with css or something.

3
  • 3
    Protip: use console.log() instead of alert() for debugging. :) Commented Sep 30, 2012 at 19:14
  • Protip #2: New code should use a strict doctype instead of transitional. While it doesn't matter in this case, since older versions of IE don't support canvas, IE is known to act quite differently in Quirks Mode. Commented Sep 30, 2012 at 20:28
  • thanks jeremy j starcher, i actually knew that, just forgot about it when i made this sample code to show what my problem was. Commented Sep 30, 2012 at 20:36

2 Answers 2

1

To get the coordinates relatively to the canvas, do this:

function hmd(e) {
    var rx = e.pageX, ry = e.pageY;
    rx -= canvas.offsetLeft;
    ry -= canvas.offsetTop;
    alert ("x: " + rx + "     y: " + ry); 
}

This assumes your canvas variable definition is global.

Edit: another method:

function hmd(e) {
    var rx, ry;
    if(e.offsetX) {
        rx = e.offsetX;
        ry = e.offsetY;
    }
    else if(e.layerX) {
        rx = e.layerX;
        ry = e.layerY;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here's what I've been using for my latest experimentation. It works with damn near everything: Borders, paddings, position:fixed elements offsetting the HTML element, etc. It also works on all touch devices and even if the browser is zoomed.

http://jsfiddle.net/simonsarris/te8GQ/5/

var stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(can, undefined)['paddingLeft'], 10) || 0;
var stylePaddingTop = parseInt(document.defaultView.getComputedStyle(can, undefined)['paddingTop'], 10) || 0;
var styleBorderLeft = parseInt(document.defaultView.getComputedStyle(can, undefined)['borderLeftWidth'], 10) || 0;
var styleBorderTop = parseInt(document.defaultView.getComputedStyle(can, undefined)['borderTopWidth'], 10) || 0;
var html = document.body.parentNode;
var htmlTop = html.offsetTop;
var htmlLeft = html.offsetLeft;

function getMouse(e) {
    var element = can,
        offsetX = 0,
        offsetY = 0,
        mx, my;

    // Compute the total offset
    if (element.offsetParent !== undefined) {
        do {
            offsetX += element.offsetLeft;
            offsetY += element.offsetTop;
        } while ((element = element.offsetParent));
    }

    // Add padding and border style widths to offset
    // Also add the <html> offsets in case there's a position:fixed bar
    offsetX += stylePaddingLeft + styleBorderLeft + htmlLeft;
    offsetY += stylePaddingTop + styleBorderTop + htmlTop;

    mx = e.pageX - offsetX;
    my = e.pageY - offsetY;

    // We return a simple javascript object (a hash) with x and y defined
    return {
        x: mx,
        y: my
    };
}

1 Comment

im going to have to read this code carefully to be able to understand it and actually use it, thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.