0
我正在嘗試使用canvas
來製作pong副本。然而,我似乎誤解了座標系在畫布上對事件的作用。無法在canvas中使用mousemove事件處理程序繪製正確位置的矩形
我創建了playerPaddle
類。有了這個班我想繪製槳的中心正是在鼠標懸停:
// Paddle Object
function Paddle(h, w, x, y, fill) {
this.h = h;
this.w = w;
this.midH = h/2;
this.x = x;
this.y = y;
this.fill = fill;
}
Paddle.prototype.draw = function(ctx) {
ctx.fillStyle = this.fill;
ctx.fillRect(this.x, this.y, this.w, this.h);
}
Paddle.prototype.updatePos = function(y) {
this.y = y - this.midH
}
我認爲正確的方法來抵消槳,使槳葉的中心在mousemove
事件會通過從槳的新位置減去槳的一半高度來繪製矩形,就像我在上面的updatePos
方法中所做的那樣。
但是,這似乎不能正常工作,因爲它正在繪製我的槳的頂部正好發生在mousemove
事件的位置。
但是,如果我從事件的y位置減去this.h
,這對我來說絕對沒有意義。
下面是我用來實例化槳的代碼,將事件處理函數添加到canvas
元素本身,以及我用來呈現所有內容的函數。
// Paddle Globals
var paddleHeight = 50,
paddleWidth = 10,
paddleOffset = 10;
var playerPaddle = new Paddle(paddleHeight, paddleWidth, paddleOffset, midY, '#FFFFFF');
// Does the actual rendering
function render() {
ctx.clearRect(0, 0, cWidth, cHeight);
playerPaddle.draw(ctx);
}
//Event Handlers
canvas.addEventListener('mousemove', function(e) {
e.preventDefault();
var position = canvas.getBoundingClientRect();
var y = e.clientY - position.top;
playerPaddle.updatePos(y);
}, false);
而且,這裏是我描述行爲的一個例子:http://jsfiddle.net/u57QD/
Arggh ......所以我的畫布的理解座標系是正確的,只是我有一些愚蠢的CSS的方式。感謝您發現這一點。 –
是的,祝你好運! :D –
@Nic Young Btw,我通常使用canvas.offsetTop獲得上邊距:D –