簡體   English   中英

如何在javascript畫布上使用鼠標接近來反轉我圈子的方向?

[英]How do I invert the direction of my circles with mouse proximity on javascript canvas?

當鼠標靠近時,我想交換圓圈的方向,但我正在努力弄清楚如何。

要溫柔,我是新手。

  • conte只是背景和我說的版本c.something

代碼

 var canvas = document.querySelector('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var conte = canvas.getContext('2d'); var l = 200; var dl = 7; var radius = 30; var mouse = { x: undefined, y: undefined } window.addEventListener('mousemove', function(event) { mouse.x = event.x; mouse.y = event.y; console.log(mouse); }) function animate() { requestAnimationFrame(animate); conte.fillStyle = 'rgba(255, 255, 255, 0.05)'; conte.fillRect(0, 0, canvas.width, canvas.height); conte.beginPath(); conte.arc(l, 200, radius, 0, Math.PI * 2, false); conte.strokeStyle = '#E3DACD'; conte.stroke(); conte.fillStyle = '#B8B0A6'; conte.fill(); if (l + radius > innerWidth || l - radius < 0) { dl = -dl; } l += dl; conte.fillStyle = 'rgba(255, 255, 255, 0.05)'; conte.fillRect(0, 0, canvas.width, canvas.height); conte.beginPath(); conte.arc(l, 300, radius, 0, Math.PI * 2, false); conte.strokeStyle = '#B0B1A1'; conte.stroke(); conte.fillStyle = '#98998B'; conte.fill(); conte.fillStyle = 'rgba(255, 255, 255, 0.05)'; conte.fillRect(0, 0, canvas.width, canvas.height); conte.beginPath(); conte.arc(l, 400, radius, 0, Math.PI * 2, false); conte.strokeStyle = '#6C7974'; conte.stroke(); conte.fillStyle = '#545E5A'; conte.fill(); conte.fillStyle = 'rgba(255, 255, 255, 0.05)'; conte.fillRect(0, 0, canvas.width, canvas.height); conte.beginPath(); conte.arc(l, 500, radius, 0, Math.PI * 2, false); conte.strokeStyle = '#935F39'; conte.stroke(); conte.fillStyle = '#7D5130'; conte.fill(); conte.fillStyle = 'rgba(255, 255, 255, 0.05)'; conte.fillRect(0, 0, canvas.width, canvas.height); conte.beginPath(); conte.arc(l, 100, radius, 0, Math.PI * 2, false); conte.strokeStyle = '#E7B99F'; conte.stroke(); conte.fillStyle = '#CFA58E'; conte.fill(); }; if (mouse.x > radius +10 || mouse.x < radius) { if (l + radius > innerWidth || l - radius < 0) { dl = -dl; } l -= dl; }; animate(); 
 <canvas id="canvas"> </canvas> 

我覺得這是結束。

你不比較動畫函數內的鼠標位置,所以它不會在每一幀都完成。 你也不要將鼠標位置與圓圈位置進行比較。 因此假設“l”是圓的水平位置,垂直位置是200,半徑是30:

if(mouse.y < 230 && mouse.y > 170 && mouse.x < l + 30 && mouse.x > l - 30) {
    //the mouse touches the circle
    dl = -dl;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM