1

所以我正在用 JavaScript 编写一些游戏(或者我称之为游戏)。基本上,你应该点击画布上的一个地方,玩家就会被画在那里。但是当我单击时,精灵偏移了一些量(我不完全知道多少)到鼠标上的点。我怎样才能得到它,以便精灵将准确地绘制在鼠标点上?

图片链接: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);
}
4

1 回答 1

1

如果精灵是 15x15,您希望srcXandsrcY为 0,而不是 1。请注意,您的代码在鼠标点处绘制精灵的左上角;如果你想让它居中,你需要做:

drawX = mouseX - width / 2;
drawY = mouseY - height / 2;
于 2013-11-11T21:35:07.813 回答