我的網頁上有一個機器人,機器人有一隻眼睛。我現在想讓眼睛跟着鼠標。javascript將x像素移向鼠標
所以我加載了一個畫布,找到了眼睛的x和y以及鼠標的x和y,但是現在我無法將它移向鼠標。我嘗試了一些畢達哥拉斯,結果發現與Math.atan2的角度,但不明白我在那裏,因爲零度是正確的,左是-180等...反正:我在這個爛攤子。你可以幫我嗎?我現在沒有試用碼的代碼如下:
眼睛四周有4像素的空間!謝謝!
// get canvas and context
var canvas = document.getElementById('robot');
var ctx = canvas.getContext('2d');
// wheres the eye
var x = 140, y = 80;
var rect = document.getElementById('robot').getBoundingClientRect();
var eyeX = rect.left + x;
var eyeY = rect.top + y;
// draw our robot on top of it
robot = new Image();
robot.src = "robot.png";
robot.onload = function() {
ctx.drawImage(robot, 0, 0);
};
// give our friend an eye. He has been friendly
eye = new Image();
eye.src = "eye.png";
eye.onload = function() {
ctx.drawImage(eye, x, y);
};
// Handle mouse
var mousePos;
window.onmousemove = handleMouseMove;
function handleMouseMove(event) {
event = event || window.event; // IE-ism
mousePos = {
x: event.clientX,
y: event.clientY
};
}
// animate the eye towards the mouse.
var interval = setInterval(function() {
return function() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(robot, 0, 0);
var pos = mousePos;
if (!pos) {
// no movement yet
}
else {
// change x and y based on direction
// HELP ME GUYS
}
ctx.drawImage(eye, x, y);
};
}(), 1000/40);
完整的工作答案,下面的答案幫助,但我固定它就像這樣。
// get canvas and context
var canvas = document.getElementById('robot');
var ctx = canvas.getContext('2d');
// wheres the eye
var x = 140, y = 80;
var rect = document.getElementById('robot').getBoundingClientRect();
var eyeX = rect.left + x;
var eyeY = rect.top + y;
var offSet = 4;
// draw our robot on top of it
robot = new Image();
robot.src = "robot.png";
robot.onload = function() {
ctx.drawImage(robot, 0, 0);
};
// give our friend an eye. He has been friendly
eye = new Image();
eye.src = "eye.png";
eye.onload = function() {
ctx.drawImage(eye, x, y);
};
window.onmousemove = handleMouseMove;
function draw(radianAngle) {
var newX = x + Math.cos(radianAngle) * offSet;
var newY = y + Math.sin(radianAngle) * offSet;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(robot, 0, 0);
ctx.drawImage(eye, newX, newY);
}
function handleMouseMove(e) {
e.preventDefault();
mouseX = parseInt(e.clientX);
mouseY = parseInt(e.clientY);
var dx = mouseX - eyeX;
var dy = mouseY - eyeY;
draw(Math.atan2(dy, dx));
}
嘿夥計!謝謝,我試着實施這個! – 2014-10-07 16:12:08
嘿,那裏,我的情況有點不同,因爲我沒有像弧一樣的功能,我可以提供我的角度:D所以我更新了我的問題,我如何解決它。一些罪惡和cos等...但感謝您的見解! – 2014-10-07 17:02:43
總是很高興幫助任何正在尋找知識的人! – markE 2014-10-07 17:05:36