我正在使用HTLM5畫布,我試圖製作圖像,並且輕鬆地按下鼠標光標。問題是我每次移動鼠標的圖像位置被重置爲原點(我相信)。我想保持實際的位置,並從那裏轉移到鼠標新位置。使圖像在HTML5中輕鬆跟隨鼠標畫布
這裏是我的代碼:
var AN = AN || {};
pic = new Image();
AN.initialize = function() {
//listen to mouse behavior and read every time he moves
window.addEventListener("mousemove", AN.moveMouse, false);
//load canvas
cv = $('#canvas')[0];
canvas = cv.getContext('2d');
//load image
pic.src = "http://fc01.deviantart.net/fs71/f/2014/349/b/e/i_hate_you__i_love_you__zoro_x_reader__by_riseagainstevil-d88ovwj.png";
};
AN.moveMouse = function(e) {
//get mouse position
var xPos = e.clientX;
var yPos = e.clientY;
var position = getPosition(pic);
var x = xPos - pic.width/2; //final position
var y = yPos - pic.height/2; //final position
var t = 0; //0-1, this is what you change in animation loop
var tx = position.x; //actual position of element for x
var ty = position.y; //actual position of element for y
function myLoop() {
canvas.clearRect(0, 0, 600, 600);
tx = EasingFunctions.easeInOutQuad(t) * x;
ty = EasingFunctions.easeInOutQuad(t) * y;
//if you need Y then do the same for that (ty)
// set element by tx
canvas.drawImage(pic, tx, ty, pic.width, pic.height);
position = getPosition(pic);
if (t < 1) {
t += 0.01; //determines speed
requestAnimationFrame(myLoop);
//setTimeout(myLoop, 16); //option to above
}
}
myLoop();
};
EasingFunctions = {
linear: function(t) {
return t;
},
easeInQuad: function(t) {
return t * t;
},
easeOutQuad: function(t) {
return t * (2 - t);
},
easeInOutQuad: function(t) {
return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
},
easeInCubic: function(t) {
return t * t * t;
},
easeOutCubic: function(t) {
return (--t) * t * t + 1;
},
easeInOutCubic: function(t) {
return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
},
easeInQuart: function(t) {
return t * t * t * t;
},
easeOutQuart: function(t) {
return 1 - (--t) * t * t * t;
},
easeInOutQuart: function(t) {
return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t;
},
easeInQuint: function(t) {
return t * t * t * t * t;
},
easeOutQuint: function(t) {
return 1 + (--t) * t * t * t * t;
},
easeInOutQuint: function(t) {
return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t;
}
}
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
while (element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return {
x: xPosition,
y: yPosition
};
}
$(document).ready(function() {
//initialize funtion
AN.initialize();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<section id="main">
<canvas id="canvas" width="600px" height="600px">Upgrade to modern browser in order to see this painting ;)</canvas>
</section>
如何從回到中心停止它,讓它留在實際位置的任何想法?
問候, Iniestar
就是這樣!非常感謝你。我很欣賞這個解釋,但仍然沒有得到很好的結果,因爲我對數學不太好。需要拿些書來改善它。 – iniestar 2015-03-02 16:27:38