我對從屏幕左側開始並在屏幕右上角區域結束的移動圖形有疑問。如何知道每次點擊它時移動圖形的寬度和高度?
讓我們來看看。我是這個新手。我在Canvas和JS上使用jQuery來做這件事。我有一個移動的圖形,每次點擊它(或畫布)都會改變它的顏色。
但我的問題在於以下幾點:當我點擊移動物體時,我想要那個物體告訴我它的寬度和高度。但是告訴我它的寬度和高度的人是畫布,而不是動人的身材。
我該如何改進?我做錯了什麼?
這裏是我的代碼:
<!DOCTYPE html>
<html>
<head>
<title>Moving Figure</title>
<meta charset="utf-8">
</head>
<body>
<canvas id="canvas" width="400" height="400" style="border:1px solid #000000"></canvas>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
var color = ['green', 'red', 'blue', 'purple', 'yellow'];
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var posicion = 0;
var tamano = 0;
setInterval(function() {
ctx.clearRect(0, 0, 400, 400);
ctx.fillRect(posicion, 0, tamano, 400-tamano);
posicion++;
tamano++;
if (posicion > 400){
posicion = 0;
tamano = 0;
ctx.fillStyle = color[Math.floor(Math.random() * 4)];
}
}, 30);
$("#canvas").click(function(){
ctx.fillStyle = color[Math.floor(Math.random() * 4)];
$("p").text("The Width of the figure is " + event.pageX + " and the Height is " + event.pageY);
});
</script>
<p id="texto"></p>
</body>
</html>
提前感謝!
及其對'canvas' click事件,所以'event.pageX'和'event.pageY'是畫布本身的事件。它對這個數字一無所知。您需要查看鼠標點擊的座標,取決於它是否基於其位置點擊圖形。但是你應該保留圖的'width'和'height',或者應該能夠根據你的變量'posicion'和'tamano'來計算它。 –