我是新使用畫布,所以我有幾個問題。我有這樣一個小小的遊戲,圈子以一致的速度下降,但我在確定是否選擇了一個下降的圓圈時遇到了問題。JavaScript的畫布元素 - 檢查是否點擊圈元素
所以基本上我需要幫助確定如何選擇一個移動的圓。你可以在ctx元素上添加事件監聽器嗎?如果可能的話,我也不想使用jQuery。
感謝您的任何幫助!
var myGamePiece;
var range = document.getElementById("myRange");
var rangeValue = document.getElementById("sliderValue");
var score = document.getElementById("score");
var canvas = document.getElementById("canvasElement");
var speedValue = 1;
var counter = 0;
canvas.width = 480;
canvas.height = 350;
canvas.addEventListener("click", function(){
counter += 1;
score.innerHTML = counter;
});
range.onchange = function(){
rangeValue.innerHTML = this.value;
speedValue = this.value;
};
function startGame() {
var randomXCord = Math.random() * (450 - 100) + 100;
var randomSize = Math.random()* (50 - 10) + 10; //random dot size between 100px - 10px
//check to make sure dots will not go off the side of the screen
if(randomSize >= 30){
if(randomXCord >= 400){
randomXCord -= 50;
}
}
myGamePiece = new component(10, 10, "red", randomXCord, 10, randomSize);
console.log(randomSize);
console.log(randomXCord);
myGameArea.start();
};
var myGameArea = {
start : function() {
document.body.insertBefore(canvas, document.body.childNodes[0]);
this.context = canvas.getContext("2d");
var interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, canvas.width, canvas.height);
}
};
function component(width, height, color, x, y, size) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
console.log(this.width);
this.radius = size;
this.update = function(){
ctx = myGameArea.context;
ctx.beginPath();
ctx.fillStyle = color;
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
ctx.fill();
};
};
function updateGameArea() {
myGameArea.clear();
//makes the dot go vertically down then calls update
myGamePiece.y += speedValue;
//check to see if dot if off the page
if(myGamePiece.y >= canvas.height){
myGameArea.clear();
// startGame();
//setTimeout(function() { startGame(); }, 1000);
}
myGamePiece.update();
};
從ES7開始,JavaScript使用**作爲電源操作器, – Blindman67