我正試圖在轉換後的畫布上獲取鼠標位置。這裏是我的大小調整方法:如何在轉換後的HTML5畫布上獲取鼠標位置
window.addEventListener('resize', resize);
function resize() {
screenWidth = window.innerWidth;
screenHeight = window.innerHeight;
scaleFillNative = MathMAX(screenWidth/maxScreenWidth, screenHeight/maxScreenHeight);
mainCanvas.width = screenWidth;
mainCanvas.height = screenHeight;
mainContext.setTransform(scaleFillNative, 0, 0, scaleFillNative, Math.floor((screenWidth - (maxScreenWidth * scaleFillNative))/2),
Math.floor((screenHeight - (maxScreenHeight * scaleFillNative))/2));
}
的maxScreenWidth和maxScreenHeight表示畫布應該轉變到本機屏幕尺寸。
實際調整大小工作正常。然而,問題是我試圖在畫布上的鼠標位置渲染一個圓。鼠標位置被設定爲如下:
window.addEventListener('mousemove', gameInput, false);
var mouseX, mouseY;
function gameInput(e) {
e.preventDefault();
e.stopPropagation();
mouseX = e.clientX;
mouseY = e.clientY;
}
然後它呈現像這樣:
renderCircle(mouseX/scaleFillNative, mouseY/scaleFillNative, 10);
x位置被正確地呈現。但是,當我調整窗口大小以使寬度小於高度時,它不再呈現在正確的x位置。 y位置始終偏移。
看看這個http://stackoverflow.com/questions/17130395/real-mouse-position-in-canvas – Derek
我試過了,但它有同樣的結果。 – user3024235
@ user3024235你能分享一個工作小提琴嗎? – sam