【问题标题】:I want to stop releasing particles when i keep holding the mouse click for long当我长时间按住鼠标单击时,我想停止释放粒子
【发布时间】:2017-05-28 17:04:07
【问题描述】:

这是粒子喷泉系统,我想在按住鼠标点击时停止释放粒子。即使我长时间单击并按住按钮,也只能单击一次。

var d = document, $d = $(d),
    w = window, $w = $(w),
    wWidth = $w.width(), wHeight = $w.height(),
    credit = $('.credit > a'),
    particles = $('.particles'),
    particleCount = 0,
    sizes = [
        45
    ],
    colors = [
      '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
      '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
      '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
      '#FF5722', '#795548', '#9E9E9E', '#607D8B', '#777777'
    ],
    
    mouseX = $w.width() / 2, mouseY = $w.height() / 2;

function updateParticleCount () {
  $('.particle-count > .number').text(particleCount);
};

$w
.on( 'resize' , function () {
  wWidth = $w.width();
  wHeight = $w.height();
});

$d
.on( 'mousemove touchmove' , function ( event ) {
  event.preventDefault();
  event.stopPropagation();
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
})
.on( 'mousedown touchstart' , function( event ) {
  if( event.target === credit.get(0) ){
    return;
  }
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
  var timer = setInterval(function () {
    $d
    .one('mouseup mouseleave touchend touchcancel touchleave', function () {
      clearInterval( timer );
    })
    createParticle( event );
  }, 1000 / 30) 
  
});


function createParticle ( event ) {
  var particle = $('<div class="particle"/>'),
      size = sizes[Math.floor(Math.random() * sizes.length)],
      color = colors[Math.floor(Math.random() * colors.length)],
      negative = size/2,
      speedHorz = Math.random() * 10,
      speedUp = Math.random() * 25,
      spinVal = 360 * Math.random(),
      spinSpeed = ((12 * Math.random())) * (Math.random() <=.5 ? -1 : 1),
      otime,
      time = otime = (1 + (.5 * Math.random())) * 1000,
      top = (mouseY - negative),
      left = (mouseX - negative),
      direction = Math.random() <=.5 ? -1 : 1 ,
      life = 10;
  
  particle
  .css({
    height: size + 'px',
    width: size + 'px',
    top: top + 'px',
    left: left + 'px',
    background: color,
    transform: 'rotate(' + spinVal + 'deg)',
    webkitTransform: 'rotate(' + spinVal + 'deg)'
  })
  .appendTo( particles );
  particleCount++;
  updateParticleCount();
  
  var particleTimer = setInterval(function () {
    time = time - life;
    left = left - (speedHorz * direction);
    top = top - speedUp;
    speedUp = Math.min(size, speedUp - 1);
    spinVal = spinVal + spinSpeed;
    
    
    particle
    .css({
      height: size + 'px',
      width: size + 'px',
      top: top + 'px',
      left: left + 'px',
      opacity: ((time / otime)/2) + .25,
    	transform: 'rotate(' + spinVal + 'deg)',
    	webkitTransform: 'rotate(' + spinVal + 'deg)'
    });
    
    if( time <= 0 || left <= -size || left >= wWidth + size || top >= wHeight + size ) {
      particle.remove();
  		particleCount--;
      updateParticleCount();
      clearInterval(particleTimer);
    }
  }, 1000 / 50);  
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

这是粒子喷泉系统,我想在按住鼠标点击时停止释放粒子。即使我长时间单击并按住按钮,也只能单击一次。

【问题讨论】:

  • 你最后一段中的文字似乎矛盾:当我一直按住时停止释放......应该可以工作......甚至......按住按钮。您希望它在按住鼠标按钮时停止或工作?
  • sn-p 能正常工作吗?它不适合我,但你的想法看起来很有趣,所以我希望看到它付诸实践。如果我了解您的需求-假设它是“当我按住鼠标按钮一段时间后停止喷泉”,那么您可能希望在 mousedown 事件上使用 setTimeout() 并在鼠标向上使用 clearTimeout() 。首先,您设置了喷泉应该观察到的一些全局“停止”变量,然后在 mouseup 上重置它。同样在 mouseup 上,您可以清除计时器以防它尚未触发。

标签: javascript jquery


【解决方案1】:

有一个错误,您必须将.one('mouseup mouseleave touchend touchcancel touchleave' 更正为on 而不是one

而且类particles的元素也不存在,因为你没有任何html代码。

试试这个:

var d = document, $d = $(d),
    w = window, $w = $(w),
    wWidth = $w.width(), 
    wHeight = $w.height(),
    credit = $('.credit > a'),
    particles = $('.particles'),
    particleCount = 0,
    maxTime = 30,
    sizes = [
            15, 19, 24, 33, 40, 9, 20, 30, 45
        ],

    colors = [
      '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
      '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
      '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
      '#FF5722', '#795548', '#9E9E9E', '#607D8B', '#777777'
    ],
    
    mouseX = $w.width() / 2,
    mouseY = $w.height() / 2;

function updateParticleCount ()
{
  $('.particle-count > .number').text(particleCount);
};

$w.
on( 'resize' , function () {
  wWidth = $w.width();
  wHeight = $w.height();
});

$d.
on( 'mousemove touchmove' , function ( event ) {
  event.preventDefault();
  event.stopPropagation();
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
})
.on( 'mousedown touchstart' , function( event ) {
  if( event.target === credit.get(0) ){
    return;
  }
  mouseX = event.clientX;
  mouseY = event.clientY;
  
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
  
  var counter = 0;
  
  var timer = setInterval(function () {
    if (counter < maxTime) {
      createParticle( event );
    } else {
      clearInterval( timer );
      counter = 0;
    }
    counter++;
    
  }, 1000 / 30);
  
  $d.
  on('mouseup mouseleave touchend touchcancel touchleave', function () {
    clearInterval( timer );
  });
});


function createParticle ( event ) 
{

  var particle = $('<div class="particle"/>'),
      size = sizes[Math.floor(Math.random() * sizes.length)],
      color = colors[Math.floor(Math.random() * colors.length)],
      negative = size/2,
      speedHorz = Math.random() * 1.0,
      speedUp = Math.random() * 2.5,
      spinVal = 360 * Math.random(),
      spinSpeed = ((12 * Math.random())) * (Math.random() <=.5 ? -1 : 1),
      otime,
      time = otime =  (1 + (.5 * Math.random())) * 1000,
      top = (mouseY - negative),
      left = (mouseX - negative),
      direction = Math.random() <=.5 ? -1 : 1 ,
      life = 10;
  
  particle
  .css({
    height: size + 'px',
    width: size + 'px',
    top: top + 'px',
    left: left + 'px',
    background: color,
    transform: 'rotate(' + spinVal + 'deg)',
    webkitTransform: 'rotate(' + spinVal + 'deg)'
  })
  .appendTo( particles );
  particleCount++;
  updateParticleCount();
  
  var particleTimer = setInterval(function () {
    time = time - life;
    left = left - (speedHorz * direction);
    top = top - speedUp;
    speedUp = Math.min(size, speedUp - 1);
    spinVal = spinVal + spinSpeed;
    
    
    particle
    .css({
      height: size + 'px',
      width: size + 'px',
      top: top + 'px',
      left: left + 'px',
      opacity: ((time / otime)/2) + .25,
    	transform: 'rotate(' + spinVal + 'deg)',
    	webkitTransform: 'rotate(' + spinVal + 'deg)'
    });
    
    if( time <= 0 || left <= -size || left >= wWidth + size || top >= wHeight + size ) {
      particle.remove();
  		particleCount--;
      updateParticleCount();
      clearInterval(particleTimer);
    }
  }, 1000 / 50);  
}
.particles {
  width: 500px;
  height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<html>
<body>
  <div class="particles">
  </div>
</body>
</html>

更新:现在如果您按住按钮太久,它会按要求停止。更改变量 ma​​xTime 的值进行调整。

更新 2:按照 OP 的要求,以下是如何将文本添加到粒子中:

var d = document, $d = $(d),
    w = window, $w = $(w),
    wWidth = $w.width(), 
    wHeight = $w.height(),
    credit = $('.credit > a'),
    particles = $('.particles'),
    particleCount = 0,
    maxTime = 30,
    sizes = [
            45, 25
        ],

    colors = [
      '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
      '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
      '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
      '#FF5722', '#795548', '#9E9E9E', '#607D8B', '#777777'
    ],
    
    mouseX = $w.width() / 2,
    mouseY = $w.height() / 2;

function updateParticleCount ()
{
  $('.particle-count > .number').text(particleCount);
};

$w.
on( 'resize' , function () {
  wWidth = $w.width();
  wHeight = $w.height();
});

$d.
on( 'mousemove touchmove' , function ( event ) {
  event.preventDefault();
  event.stopPropagation();
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
})
.on( 'mousedown touchstart' , function( event ) {
  if( event.target === credit.get(0) ){
    return;
  }
  mouseX = event.clientX;
  mouseY = event.clientY;
  
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
  
  var counter = 0;
  
  var timer = setInterval(function () {
    if (counter < maxTime) {
      createParticle( event );
    } else {
      clearInterval( timer );
      counter = 0;
    }
    counter++;
    
  }, 1000 / 30);
  
  $d.
  on('mouseup mouseleave touchend touchcancel touchleave', function () {
    clearInterval( timer );
  });
});


function createParticle ( event ) 
{

  var particle = $('<div class="particle" id="'+particleCount+'"/>'),
      size = sizes[Math.floor(Math.random() * sizes.length)],
      color = colors[Math.floor(Math.random() * colors.length)],
      negative = size/2,
      speedHorz = Math.random() * 1.0,
      speedUp = Math.random() * 2.5,
      spinVal = 360 * Math.random(),
      spinSpeed = ((12 * Math.random())) * (Math.random() <=.5 ? -1 : 1),
      otime,
      time = otime =  (1 + (.5 * Math.random())) * 1000,
      top = (mouseY - negative),
      left = (mouseX - negative),
      direction = Math.random() <=.5 ? -1 : 1 ,
      life = 10;
  
  addRandomOperatorToParticle(particle);
    
  particle
  .css({
    height: size + 'px',
    width: size + 'px',
    "font-size": size / 1.78 + 'px',
    "text-align": 'center',
    "vertical-align": 'middle',
    "line-height": size + 'px',
    top: top + 'px',
    left: left + 'px',
    background: color,
    transform: 'rotate(' + spinVal + 'deg)',
    webkitTransform: 'rotate(' + spinVal + 'deg)',
  })
  .appendTo( particles );
  particleCount++;
  updateParticleCount();
  
  var particleTimer = setInterval(function () {
    time = time - life;
    left = left - (speedHorz * direction);
    top = top - speedUp;
    speedUp = Math.min(size, speedUp - 1);
    spinVal = spinVal + spinSpeed;
    
    particle
    .css({
      height: size + 'px',
      width: size + 'px',
      top: top + 'px',
      left: left + 'px',
      opacity: ((time / otime)/2) + .25,
    	transform: 'rotate(' + spinVal + 'deg)',
    	webkitTransform: 'rotate(' + spinVal + 'deg)'
    });
    
    if( time <= 0 || left <= -size || left >= wWidth + size || top >= wHeight + size ) {
      particle.remove();
  		particleCount--;
      updateParticleCount();
      clearInterval(particleTimer);
    }
  }, 1000 / 50);  
}

function addRandomOperatorToParticle(element)
{
    var operators = new Array("+","-","%","x");
    var operator = operators[Math.floor(Math.random() * operators.length)];
    
    $(element).html(operator);
}
.particles {
  width: 500px;
  height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<html>
<body>
  <div class="particles">
  </div>
</body>
</html>

请注意,我添加了一个新函数 addRandomOperatorToParticle 来完成这项工作,并且我还修改了 css。您可以在此函数内扩展运算符列表。或者重写它,使其将数组作为第二个参数,其中包含所有所需的运算符/文本。

【讨论】:

  • 谢谢!你修改了喷泉效果,但是我得到了我想要的。我只需要暂停鼠标点击。
  • 我没有定义最大时间间隔
  • 是的,很抱歉修改它,我只添加了几个尺寸。最后我忘了把它重置为你的值。顺便说一句,很酷的动画!
  • 感谢您的赞赏。我有一个查询。如果你能帮忙,那将是我的荣幸。我只想在调整块上画一些运算符。像 if +, -, ×, % 等等。我们也可以只画一个运算符。但我真的需要把它画在喷泉块上。
  • 太好了,感谢您的帮助!
【解决方案2】:

这是一个 sn-p,它显示了一种使用 mousedown 来暂停效果的方法,并带有暂停操作之前的时间延迟的视觉指示器。

var halt = false;   // controls running or stopped animation.

// function to move the red block to the right
function moove(){ 
  var bobEle = $('#bob');     // cache the red block handle;
  var left = bobEle.position().left;  // read the initial left position;
  var moveLoop = setInterval(function(){
    if (halt) { return false}       // when halt is true we abandon animation.
    left = left + 10;               // otherwise we calc the new left position
    if (left > 200 ) { left = 0 };  // and restart if past the end point we decided on
    $('#bob').css({left : left});   // and move the red square.   
  }, 100)                           // we do this every 10th of a sec to give a decent frame rate.
}

// this function changes the display to Run/Stop depending on halt variable.
// we could also use this to set the value of halt.
function showHalt() {
  var status='Run';
  if (halt) { status = 'Halt'}; 
  $('#status').html(status);
}

// The tick, interval and setBar() func control the initial blue bar width, and its countdown.
var tick = 60;
var interval = 6;
function setBar(){
  barEle.show();
  barEle.css({width : tick, visibility: 'visible'});  
}

var barEle = $('#bar');    
var barTimer = 0;

// We use a listener for the document mousedown event to start the bar countdown.
$(document)
  .on('mousedown', function(e){
    // countdown bar  
    setBar();

    // the barTimer function repeats every 50 millisecs to give a pleasing countdown 
    // When tick = 0 we set the halt variable true to stop the red square animation in moove()
    barTimer = setInterval(function(){ 
        tick = tick - interval;
        
        if (tick === 0) {
          clearInterval(barTimer);
          halt = true;
          setBar();
          showHalt();
          return 0;
        }
        setBar();
      }
      , 50
      )
  })

  // If the user lets the mouse button up we let the animation proceed by setting halt=false
  // and stop the bar from animating. We also hide the bar here.
$(document)
  .on('mouseup', function(e){
    clearInterval(barTimer);
    tick = 60;
    halt = false;
    barEle.css({visibility: 'hidden'});
    showHalt();
    })
  
// The start button starts the anumation.
$('#btnStart').on('click', function(e){
  e.stopPropagation();
  moove();
  showHalt();
})
$('#btnStart').on('mouseup mousedown', function(e){
  e.stopPropagation();
})  
  
div span
{
margin: 5px;
}

#bob
{
position:absolute;
border: 1px solid red;
background-color: red;
width: 20px;
height: 20px;
}
#bar
{
display: inline-block;
width:60px;
height: 5px;
background-color: blue;
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='info'>Click the Start button to commence, then hold mousedown anywhere on document to pause.</div>
<div id='display'></div>
<div><button id='btnStart'>Start</button><span id='status'></span></div>
<div><div id='bar'></div></div>

<div id='bob'></div>

【讨论】:

    猜你喜欢
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多