如何使用 Vanilla JS 使用 clickEventListener 在紅色和藍色之間切換
P粉523625080
P粉523625080 2024-04-03 20:19:03
0
2
384

首先,我創建兩個函數藍色和紅色。

function drawBlueCircle(){
    ctx.fillStyle = 'blue';
    ctx.beginPath();
    ctx.arc(mouse.x,mouse.y,50,0,Math.PI *2)
    ctx.fill();
}

function drawRedCircle(){
    ctx.fillStyle = 'red'
    ctx.beginPath();
    ctx.arc(mouse.x,mouse.y,50,0,Math.PI * 2);
    ctx.fill();
}

這裡我在 For 迴圈中使用 if 語句建立一個 clickEventListener

#
canvas.addEventListener('click',function(event){
    mouse.x = event.x,
    mouse.y = event.y
    
    for(let i=0;i<event.length;i++){
        
        (i%2==0)? drawBlueCircle():drawRedCircle() // here i am trying to alter my clicks using for loops. 
    }
})

我的錯誤是: 即使單擊滑鼠後,它仍然保持紅色。我透過其他 eventListener mousemove 獲得了這种红色,但這不是問題。

P.S.:這不是完整的程式碼。我只給了我無法解決的一個(上面)。

我嘗試了上面的程式碼,但無法改變顏色。

P粉523625080
P粉523625080

全部回覆(2)
P粉068486220

最簡單的選擇是使用布林變數來儲存您期望的顏色,然後在每次點擊時反轉它:

function drawBlueCircle() {
  console.log('drawBlueCircle called')
}

function drawRedCircle() {
  console.log('drawRedCircle called')
}

// This variable tracks which color we are up to
let isBlue = true

// Added the listener to 'window' for the sake of the example
window.addEventListener('click', function(event) {
  // Run the expected function
  if (isBlue) {
    drawBlueCircle()
  } else {
    drawRedCircle()
  }
  
  // Invert the next color
  isBlue = !isBlue
})
Click anywhere
P粉790819727

您應該維護下一個要繪製的顏色的引用,而不是使用循環。此外,如果您將顏色(以及上下文和事件)作為函數參數傳遞,則可以將函數簡化為一個:drawCircle,並使用該顏色來確定圓的填滿顏色。

// Pass in the context, event, and colour to the
// function so you can use them
function drawCircle(ctx, event, color) {
  ctx.fillStyle = color;
  ctx.beginPath();
  ctx.arc(event.x, event.y, 50, 0, Math.PI *2);
  ctx.fill();
}

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

// Initialise the color
let color = 'red';

canvas.addEventListener('click', event => {
  
  // Draw a circle with the current colour
  drawCircle(ctx, event, color);

  // Switch the color
  color = color === 'red' ? 'blue' : 'red';
});
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!