Cara bertukar antara merah dan biru menggunakan clickEventListener menggunakan Vanilla JS
P粉523625080
P粉523625080 2024-04-03 20:19:03
0
2
386

Pertama, saya mencipta dua fungsi biru dan merah.

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();
}

Di sini saya menggunakan pernyataan if dalam gelung For untuk mencipta 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. 
    }
})

Kesilapan saya ialah: Walaupun selepas mengklik tetikus, ia tetap merah. Saya mendapat warna merah ini dengan eventListener mousemove lain tetapi itu bukan masalahnya.

P.S.: Ini bukan kod lengkap. Saya hanya memberikan yang saya tidak dapat menyelesaikan (di atas).

Saya cuba kod di atas tetapi tidak dapat menukar warna.

P粉523625080
P粉523625080

membalas semua(2)
P粉068486220

Pilihan paling mudah ialah menggunakan pembolehubah boolean untuk menyimpan warna yang anda inginkan dan kemudian terbalikkannya pada setiap klik:

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

Anda harus mengekalkan rujukan kepada warna seterusnya yang akan dilukis dan bukannya menggunakan gelung. Selain itu, jika anda menghantar warna (dan konteks serta peristiwa) sebagai hujah fungsi, anda boleh memudahkan fungsi kepada hanya satu: drawCircle dan menggunakan warna itu untuk menentukan warna isian bulatan.

// 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';
});
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!