我製作了一個小遊戲,玩家必須在其中找到我在圖片中某處放置的角色。我做到了這樣,這張圖片就是一個畫布元素的背景圖片。然後我畫了一個黑色矩形,覆蓋整個畫布,以便背景圖像不可見。最後,我創建了一個名爲clearCircle的函數,它清除黑色矩形的圓形區域,以便背景圖像僅在該區域內可見。當鼠標在畫布上時,如何在Javascript中使用我的鼠標移動功能?
最終,我真的希望讓clearCircle函數的座標更改爲鼠標在畫布上的位置,並隨鼠標不斷移動。當正常工作時,當鼠標在畫布上時,這應該會產生幾乎手電筒亮暗的效果。
*我有一個包含「mousemove」的事件偵聽器,雖然它似乎不能與我寫的其他代碼一起工作。我對編程相對比較陌生,所以很可能我的其他代碼也存在缺陷。
這裏是我的代碼:
<!DOCTYPE HTML>
<html><head>
<title>Where's Lumpy Space Princess?</title>
<meta charset="utf-8">
<title>Canvas Background through CSS</title>
<style type="text/css" media="screen">
a {
color: white;
}
.footer {
text-align:center;
position:fixed;
bottom: 0px;
}
canvas { background:url(cave.gif) }
body {
background-color: black;
color: white;
}
</style>
</head>
<body>
<center>
<h1> Where's Lumpy Space Princess?</h1>
<p>"Oh my glob you guys, I'm lost!"</p>
<img src="lspsay.gif">
<h2> Instructions:</h2>
<h3> L.S.P. is lost in the dark cave and can't find her way out! Fortunately, you can guide her with your flashlight!<br>
But first, you have to find her.<br>
When you find her, click on the link at the bottom of the page to move on. </h3>
<canvas id="canvas" width="1000" height="750">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var canvas
var rect
canvas=document.getElementById("canvas");
rect=canvas.getBoundingClientRect();
function getCoords(ev){
var mx;
var my;
mx = ev.clientX-rect.left;
my = ev.clientY-rect.top;
return [mx,my]; }
canvas.addEventListener("mousemove", getCoords, false);
var cover = document.getElementById("canvas"), context = cover.getContext("2d");
context.fillStyle = "black";
context.fillRect(0,0,1000,750);
function clearCircle(context,x,y,radius) {
context.save();
context.beginPath();
context.arc(x, y, radius, 0, 2*Math.PI, true);
context.clip();
context.clearRect(x-radius,y-radius,radius*2,radius*2);
context.restore();
}
while (true); {
getCoords();
clearCircle(context,clientX-rect,clientY-rect,/*radius=*/60);
}
</script>
<br>
<p> Image Source: http://s3.amazonaws.com/placester- wordpress/blogs.dir/589/files/2012/08/caveman-cave-091746.jpg<p>
<br>
<a href="myfinalproject1.html">Click Here to Move On</a>
<audio autoplay>
<source src="cave.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</center>
</body>
</html>
訂閱畫布的onmousemove事件! – doldt