我遇到了以下非常簡單的代碼,用於拖動使用javascript的正方形。它在html5畫布上繪製。儘管非常簡單,但它肯定會暴露我漂亮的JavaScript知識中的一些空白。我通常對拖放的想法(即開始拖動鼠標單擊,停止拖動鼠標釋放),但我的問題如下:在畫布上拖放 - 一些與功能相關的查詢
(1)我看不到變量e的定義,但它一直在使用。
(2)在底層的init函數中,onmousedown偵聽器似乎被附加到畫布上。但它等於函數myDown,但myDown後面沒有括號。所以myDown函數實際上並不會被執行。那麼它在做什麼呢?
在此先感謝。我試圖自己研究這個,但還沒有取得任何成功。
馬特
<html>
<head>
</head>
<body>
<section>
<div>
<canvas id="canvas" width="400" height="300">
</canvas>
</div>
<script type="text/javascript">
var canvas;
var ctx;
var x = 75;
var y = 50;
var dx = 5;
var dy = 3;
var WIDTH = 400;
var HEIGHT = 300;
var dragok = false;
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 10);
}
function draw() {
clear();
ctx.fillStyle = "#FAF7F8";
rect(0,0,WIDTH,HEIGHT);
ctx.fillStyle = "#444444";
rect(x - 15, y - 15, 30, 30);
}
function myMove(e){
if (dragok){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
}
}
function myDown(e){
if (e.pageX < x + 15 + canvas.offsetLeft && e.pageX > x - 15 +
canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop &&
e.pageY > y -15 + canvas.offsetTop){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
dragok = true;
canvas.onmousemove = myMove;
}
}
function myUp(){
dragok = false;
canvas.onmousemove = null;
}
init();
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
</script>
</section>
</body>
</html>