I'm currently working on finding the mouse coordinates on an HTML5 canvas element.
I set the canvas dimensions to 700x700. When I hover over the canvas, I aim to retrieve the X,Y coordinates of the mouse. Everything goes smoothly until I resize the canvas using CSS in the HTML file...
Check out my JavaScript file: function Sprite(path) { this.img = new Image(); this.img.onload = loaded; this.img.src = path;
function loaded()
{
console.log("Image loaded successfully");
}
}
function drawSprite(sprite, ctx)
{
console.log("Drawing image");
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("coordinates");
status.innerHTML = mouseX + " | " + mouseY;
});
this.objects = new Array();
this.objects.push(new Sprite("dog.png"));
}
function drawGame(g)
{
console.log("Here I am");
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);
}
Take a look at my HTML File
<html>
<head>
<script src="functions.js"></script>
<style>
canvas
{
width: 90%;
height: 90%;
}
</style>
</head>
<body>
<h1 id="coordinates">0 | 0</h1>
</body>
<html>