所以我正在用 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);
}