Reputation: 3946
I am attempting to locate the coordinates of the mouse on a canvas element of an HTML5 page.
I create the canvas to be a certain height and width, for example 700x700. When I mouse over the canvas, I want to be able to know the X,Y of the mouse. This works fine, until I stretch my canvas using CSS in the HTML file...
Here is my javascript file: function Sprite(path) { this.img = new Image(); this.img.onload = loaded; this.img.src = path;
function loaded()
{
console.log("Loaded picture");
}
}
function drawSprite(sprite, ctx)
{
console.log("drawing picture");
ctx.drawImage(sprite.img,10,10);
}
//------------------------------------------
function Game()
{
this.canvas = document.createElement("canvas");
document.body.appendChild(this.canvas);
this.canvas.width = 700;
this.canvas.height = 700;
this.context = this.canvas.getContext("2d");
var ctx = this.context;
ctx.canvas.addEventListener('mousemove', function(event){
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
var status = document.getElementById("coords");
status.innerHTML = mouseX+" | "+mouseY;
});
this.objects = new Array();
this.objects.push(new Sprite("dog.png"));
}
function drawGame(g)
{
console.log("I'm here");
for(var i=0;i<g.objects.length;i++)
{
drawSprite(g.objects[i], g.context);
}
}
function drawLine(g)
{
g.context.moveTo(0,0);
g.context.lineTo(100,100);
g.context.stroke();
}
//------------------
window.addEventListener('load',function(event){startgame();});
var globalGame;
function startgame()
{
globalGame = new Game();
drawGame(globalGame);
drawLine(globalGame);
}
Here is my HTML File
<html>
<head>
<script src="functions.js"></script>
<style>
canvas
{
width:90%;
height:90%;
}
</style>
</head>
<body>
<h1 id="coords">0 | 0</h1>
</body>
<html>
Upvotes: 1
Views: 4125
Reputation: 16875
The mouse coordinates are in display pixels. To convert that to canvas coordinates, you'll need to scale them accordingly.
One way of doing this is:
const canvasX = mouseX * canvas.width / canvas.clientWidth;
const canvasY = mouseY * canvas.height / canvas.clientHeight;
as shown in this example:
const status = document.getElementById("coords");
const canvas = document.createElement("canvas");
canvas.width = 700;
canvas.height = 700;
document.body.appendChild(canvas);
canvas.addEventListener('mousemove', event => {
const mouseX = event.clientX - canvas.offsetLeft;
const mouseY = event.clientY - canvas.offsetTop;
// scale mouse coordinates to canvas coordinates
const canvasX = mouseX * canvas.width / canvas.clientWidth;
const canvasY = mouseY * canvas.height / canvas.clientHeight;
status.innerHTML = `${mouseX} | ${mouseY}<br>${canvasX} | ${canvasY}`;
});
canvas {
width:250px;
height:250px;
background-color:#f0f;
}
<div id="coords">??? | ???<br>??? | ???</div>
Upvotes: 6