Javascript / HTML:如何反转函数?

时间:2017-04-21 19:14:49

标签: javascript html

尝试(并且失败)找出让这个功能切换的方法。这样,如果你做了鼠标滚轮就会完成它会回到一个圆球中。

$('html').on ('mousewheel', function (e) {
    moveAside();
  });
  function moveAside(){
    pointPreparations = function(){};
    var amountOnLeft = Math.round(mappers.length/2);
    var amountOnRight = mappers.length-amountOnLeft;
    var spaceBetweenLeft = ctx.height/amountOnLeft;
    var spaceBetweenRight = ctx.height/amountOnRight;
    console.log("Space left: " + spaceBetweenLeft + ", right:" + spaceBetweenRight);
    for(var n = 0;n != mappers.length;n++){
      mappers[n].setSpeed(40);
      if(n < amountOnLeft){
        mappers[n].setDestination(new Point(30, (spaceBetweenLeft*n)+10, 300));
      }else{
        mappers[n].setDestination(new Point((ctx.width-30), (spaceBetweenRight*(n-amountOnLeft))+10, 300));
      }
    }
  }

如果您需要完整的文档。 视图源:http://ruegg.me/ (不确定将其归类为JS或html。)

1 个答案:

答案 0 :(得分:0)

嗯,我没有更好的事情发生,所以我决定对此采取行动。以下是我提出的建议:

var disacknowledgeUntil = 0; // ignore until time.now >= this variable's time
$('html').off('mousewheel'); // remove old handlers (needed for testing from console to override website's handler)
$('html').on('mousewheel', function(e) {
    var currentTime = new Date().getTime();
    if (disacknowledgeUntil > currentTime) {
        console.log("Ignored.")
        void 0;
        return !1; // in case browser fails to acknowledge void 0 call.
    } else {
        disacknowledgeUntil = currentTime + 1250; // ignore scroll events for next 1.25 sec.
        // When I (Spencer) was testing this in Chrome, chrome would send multiple messages for a scroll event,
        // so to counter this, I put this in place to make sure scrolls are not processed multiple times.
    }
    console.log(e.originalEvent);
    if (e.originalEvent.wheelDelta >= 0) {
        // User scrolled up, so we'll reinitialize the orb.
        console.log("calling reinitialize");
        reinitializeMap(); // call reinit.
    } else {
        // user scrolled down, so break the orb and move the pieces to the side as a border.
        console.log("Calling moveAside");
        moveAside();
    }
    return !0;
});

这会导致处理程序在页面向上滚动时调用 reinitializeMap() (从而导致orb重新出现),然后在用户向下滚动时调用moveAside()

reinitializeMap()是我添加的一个函数,它几乎可以重置所有内容,因此重新绘制了一个orb,就好像页面只是刚刚加载一样:

var intervalMapper = window.setInterval(function(){ manageMappers(); draw();}, 30);
var intervalTitle = window.setInterval(function(){ manageTitle();}, 200); // increased time because of spastic blinking.
var pointPrepBackup = function(){};
var lastInit = new Date().getTime();
function reinitializeMap(){
    var currentTime = new Date().getTime();
    if(currentTime-lastInit < 1500){
        console.log("Called within last 1.5 seconds!");
        return !1; // don't reinitialize unless it has been more than 1.5 seconds since last init.
    }
    lastInit = currentTime;
    clearInterval(intervalMapper);
    intervalMapper = setInterval(function(){ manageMappers(); draw();}, 30);
    maxPoints = 200;
    mappers = [];
    pointPreparations = function(){};
      pointPrepBackup = function(){};
    zDistance = 600;

    //Sphere messing around
    baseRadius = 100;
    amount = 20;

    //var middle = (((layers-1)/2)+1);
    sphereLength = 500;
    zPlacement = zDistance/2;
    yPlacement = ctx.height/2;
    xPlacement = ctx.width/2;

   // var spacingBetweenLayers = sphereLength/layers;
    sphereLocations = [];

    perimiter = 2*Math.PI*baseRadius;
    spacing = perimiter/amount;

    mappers = [];

    for(var n = 0; n != amount; n++){
      var ratioPerimiter = (n*spacing)/perimiter;
      var angle = ratioPerimiter*360;
      var pointLocation = getFurtherPoint(xPlacement, zPlacement, toRadians(angle), baseRadius);
      //sphereLocations.push(new Point(pointLocation.a, yPlacement, pointLocation.b));

      var zDifference = Math.abs(pointLocation.b - zPlacement);//Radius
      var thisPerimiter = 2*Math.PI*zDifference;
      console.log(thisPerimiter);
      for(var m =0; m != Math.round(thisPerimiter/spacing); m++){
        var coPerimiter = (m*spacing)/thisPerimiter;//Column Perimiter
        var coAngle = coPerimiter*360+90;
        var coPointLocation = getFurtherPoint(yPlacement, zPlacement, toRadians(coAngle), zDifference);
        sphereLocations.push(new Point(pointLocation.a, coPointLocation.a, coPointLocation.b));
      }
      /*for(var m =0; m != amount; m++){
        var coPerimiter = (m*spacing)/perimiter;//Column Perimiter
        var coAngle = coPerimiter*360;
        var coPointLocation = getFurtherPoint(yPlacement, zPlacement, toRadians(coAngle+angle), baseRadius);
        sphereLocations.push(new Point(xPlacement, coPointLocation.a, coPointLocation.b));
      }*/
    }
    //ANGLE X, ANGLE Y

    for(var n = 0; n != sphereLocations.length;n++){
      randomX = (Math.floor(Math.random() * ctx.width) + 1);
      randomY = (Math.floor(Math.random() * ctx.height) + 1);
      mappers.push(new Mapper(randomX, randomY, ((Math.floor(Math.random() * 9) + 0)), sphereLocations[n], 0));
    }

    x = ctx.width;

    // canvas.removeEventListener('mousemove'); // remove old event listener
    $('canvas').off();
    $('canvas').on('mousemove', function(evt) {
      x = evt.clientX - canvas.getBoundingClientRect().left;
    });

    pointPrepBackup = function(){
      for(var n = mappers.length -1; n >= 0;n--) {
        var mapper = mappers[n];
        var currentAngle = Math.atan2(mapper.getZ() - zPlacement, mapper.getX() - xPlacement);
        var currentDistance = Math.sqrt(Math.pow((mapper.getZ()-zPlacement), 2)+Math.pow((mapper.getX()-xPlacement), 2));
        var newPoint = getFurtherPoint(xPlacement, zPlacement, currentAngle+getAngleAddition(), currentDistance);
        mapper.setDestination(new Point(newPoint.a, mapper.getY(), newPoint.b));
      }
    };

    pointPreparations = pointPrepBackup;

}

reinitializeMap()还有一个预防性的peudo-timer,以防止它过于频繁地被调用;但是,我在将disacknowledgeUntil添加到处理函数之前添加了它。我认为lastInit现在已经添加了disacknowledgeUntil,我认为不需要var disacknowledgeUntil = 0; // ignore until time.now >= this variable's time var orbState = !0; // true (!0) if showing orb; false if not showing orb (showing side bars) $('html').off('mousewheel'); // remove old handlers (needed for testing from console to override website's handler) $('html').on('mousewheel', function(e) { var currentTime = new Date().getTime(); if (disacknowledgeUntil > currentTime) { console.log("Ignored.") void 0; return !1; // in case browser fails to acknowledge void 0 call. } else { disacknowledgeUntil = currentTime + 1250; // ignore scroll events for next 1.25 sec. // When I (Spencer) was testing this in Chrome, chrome would send multiple messages for a scroll event, // so to counter this, I put this in place to make sure scrolls are not processed multiple times. } console.log(e.originalEvent); if (!orbState) { // not showing orb right now console.log("calling reinitialize"); reinitializeMap(); // call reinit to display orb } else { // showing orb right now console.log("Calling moveAside"); moveAside(); // transition from orb to sidebars } orbState = !orbState; // toggle state return !0; }); ,但我会留给您测试。

有关此工作的完整示例以及我使用的完整脚本,您可以查看以下jsfiddle:https://jsfiddle.net/SpencerD/jmcrxjv5/3/

为了最佳地查看结果页面,以下内容将显示为整页:https://jsfiddle.net/SpencerD/jmcrxjv5/3/embedded/result/

如果你想让它再次向下滚动会导致页面恢复到一个orb,上面的代码只需要进行以下修改:

import React from 'react'
import api from '../shared/api'
import ForecastBox from './ForecastBox'
import DropdownSelector from './DropdownSelector'

const regions = [
  {
    name: 'Santa Cruz',
    id: '2958',
    spots:
    [
      { name: 'Steamer Lane', id: '4188' },
      { name: 'Four Mile', id: '5023' },
      { name: 'Waddell Creek', id: '5021' },
      { name: 'Mitchell\'s Cove', id: '5028' },
      { name: '26th Ave', id: '5030' },
    ],
  },
  {
    name: 'North Orange Country',
    id: '2143',
    spots:
    [
      { name: 'Newport', id: '1241' },
      { name: 'HB', id: '3421' },
    ],
  },
]

class ForecastPage extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      selectedRegion: null,
      selectedSpot: null,
      forecast: null,
    }

    this.regionSpotList = regions
    this.updateSpot = this.updateSpot.bind(this)
    this.updateRegion = this.updateRegion.bind(this)
  }

  updateRegion(region) {
    this.setState({
      selectedRegion: region,
      forecast: null,
    })

    api.fetchSpot(region.id)
    .then((forecast) => {
      this.setState({
        forecast,
      })
    })
  }

  updateSpot(spot) {
    this.setState({
      selectedSpot: spot,
      forecast: null,
    })

    api.fetchSpot(spot.id)
    .then((forecast) => {
      this.setState({
        forecast,
      })
    })
  }

  render() {
    return (
      <div>
        <div className="container-fluid row region-spot-select">
          <DropdownSelector
            options={this.regionSpotList}
            onSelect={this.updateRegion}
            title={this.state.selectedRegion == null ? 'Select Your Region' : this.state.selectedRegion.name}
            keyName={'region-selector'}
            id={'region-selector-dropdown'}
          />
          {this.state.selectedRegion != null &&
            <DropdownSelector
              options={this.state.selectedRegion.spots}
              onSelect={this.updateSpot}
              title={this.state.selectedSpot == null ||
              !this.state.selectedRegion.spots.includes(this.state.selectedSpot) ?
              'Select A Spot' :
              this.state.selectedSpot.name}
              keyName={'spot-selector'}
              id={'spot-selector-dropdown'}
            />
          }
        </div>
        <div>
          {!this.state.forecast ?
            <div>
              Select A Region
            </div>
          : <ForecastBox forecast={this.state.forecast} /> }
        </div>
      </div>
    )
  }
}

export default ForecastPage

我没有测试过这段代码,但它应该尽我所能。