Question

So I was coding some game (or what I call game) in JavaScript. And basically, you're supposed to click a place on the canvas and the player will be drawn there. But when I clicked the sprite was offset by some amount (I don't exactly know how much) to the point on the mouse. How can I get it so that the sprite will be draw exactly on the point of the mouse?

Link to image: http://i.imgur.com/Wnqb3L6.jpg?1

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

canvas.addEventListener('mousemove', mouseMoved, false);
canvas.addEventListener('click', drawPlayerPos, false);

var spriteSheet = new Image();
spriteSheet.src = 'spritesheet.png';
spriteSheet.addEventListener('load', init, false);

var gameWidth = canvas.width;
var gameHeight = canvas.height;

function init()
{
    drawPlayerPos();
}


var mouseX;
var mouseY;

function mouseMoved(e)
{
    mouseX = e.pageX - canvas.offsetLeft;
    mouseY = e.pageY - canvas.offsetTop;
    document.getElementById('mouseCoors').innerHTML = 'X: ' + mouseX + ' Y: ' + mouseY;
}

function drawPlayerPos()
{
    var srcX = 1;
    var srcY = 1;
    var drawX = mouseX;
    var drawY = mouseY;
    var width = 15;
    var height = 15;
    ctx.drawImage(spriteSheet,srcX,srcY,width,height,drawX,drawY,width,height);
}
Was it helpful?

Solution

If the sprite is 15x15, you want srcX and srcY to be 0, not 1. And note that your code draws the top left corner of the sprite at the mouse point; if you want it to be centered you need to do:

drawX = mouseX - width / 2;
drawY = mouseY - height / 2;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top