Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 18.12.2015, 01:03
Интересующийся
Отправить личное сообщение для walker1232 Посмотреть профиль Найти все сообщения от walker1232
 
Регистрация: 28.11.2015
Сообщений: 24

Canvas диаграмма js, нужно доработать
Ребят как сделать чтобы после запуска первого кружка(или когда дошло до 5 процентов), начался запуск второго, потом после запуска второго начался запуск третьего, чтобы не ждать пока все по 1-му загрузятся и чтобы красиво было )
<canvas class="canvas" data-bg-color="#e4e4e4" data-coloor="#222" data-color="#16a6b6" data-percent="40" height="120" width="120"></canvas>
<canvas class="canvas" data-bg-color="#e4e4e4" data-coloor="#222" data-color="#16a6b6" data-percent="50" height="120" width="120"></canvas>
<canvas class="canvas" data-bg-color="#e4e4e4" data-coloor="#222" data-color="#16a6b6" data-percent="60" height="120" width="120"></canvas>
<canvas class="canvas" data-bg-color="#e4e4e4" data-coloor="#222" data-color="#16a6b6" data-percent="70" height="120" width="120"></canvas>
<canvas class="canvas" data-bg-color="#e4e4e4" data-coloor="#222" data-color="#16a6b6" data-percent="80" height="120" width="120"></canvas>

/**
   * @class Circle
   * @constructor
   */
  var Circle = function (canvas, callback) {
    /**
     * @type {HTMLCanvasElement}
     * @private
     */
    this._canvas = canvas;
    /**
     * @type {CanvasRenderingContext2D}
     * @private
     */
    this._ctx = canvas.getContext('2d');
    /**
     * @type {number}
     * @private
     */
    this._animateSpeed = 20;
    /**
     * @type {number}
     * @private
     */
    this._endProgress = Number(this._canvas.getAttribute('data-percent'));
    /**
     * @type {string}
     * @private
     */
    this._bgColor = this._canvas.getAttribute('data-bg-color');
    /**
     * @type {string}
     * @private
     */
    this._color = this._canvas.getAttribute('data-color');
    this._coloor = this._canvas.getAttribute('data-coloor');
    /**
     * @type {Array<function>}
     * @private
     */
    this._onReadyCallbacks = [];
    /**
     * @type {boolean}
     * @private
     */
    this._isReady = false;
    /**
     * @type {function}
     * @private
     */
    this._onEndAnimation = callback;
    /**
     * @type {number}
     * @private
     */
    this._radius = this._canvas.width / 2 - 3;
    /**
     * @type {number}
     * @private
     */
    this._width = this._canvas.width;
    /**
     * @type {number}
     * @private
     */
    this._height = this._canvas.height;
    this._onScroll = this._onScroll.bind(this);
    this._initialize();
  };
  /**
   * @lends Circle#
   */
  Circle.prototype = {
    setReady: function () {
      this._isReady = true;
      this._onReadyCallbacks.forEach(function (callback) {
        callback.call(this);
      }, this);
      this._onReadyCallbacks = [];
    },
    /**
     * @param {function} callback
     * @private
     */
    _onReady: function (callback) {
        if (this._isReady) {
          callback.call(this);
        } else {
          this._onReadyCallbacks.push(callback);
        }
      },
      /**
       * @returns {boolean}
       * @private
       */
      _isVisible: function () {
        var scroll = this._getScrollTop();
        var offset = this._canvas.offsetTop;
        return (scroll < offset) && (scroll + innerHeight > offset + this._canvas.height);
      },
      /**
       * @returns {number}
       * @private
       */
      _getScrollTop: function () {
        return document.body.scrollTop || document.documentElement.scrollTop;
      },
      /**
       * @private
       */
      _animate: function () {
        var time = this._endProgress * this._animateSpeed;
        Circle._animate({
          duration: time,
          step: this._redraw.bind(this),
          complete: this._onEndAnimation
        });
        window.removeEventListener('scroll', this._onScroll, false);
      },
      /**
       * @private
       */
      _clear: function () {
        this._canvas.width = this._canvas.width;
      },
      /**
       * @param {number} progress
       * @private
       */
      _draw: function (progress) {
        var angleStart = - Math.PI / 2;
        var angleEnd = angleStart + (2 * Math.PI * this._endProgress / 100) * progress;
        this._ctx.beginPath();
        this._ctx.strokeStyle = this._bgColor;
        this._ctx.lineWidth = 2;
        this._ctx.arc(this._width / 2, this._height / 2, this._radius, 0, Math.PI * 2, false);
        this._ctx.stroke();
        this._ctx.beginPath();
        this._ctx.strokeStyle = this._color;
        this._ctx.lineWidth = 2;
        this._ctx.arc(this._width / 2, this._height / 2, this._radius, angleStart, angleEnd, false);
        this._ctx.stroke();
        this._ctx.fillStyle = this._coloor;
        this._ctx.font = "bold 33px Verdana";
        var text = Math.floor(this._endProgress * progress) + "%";
        var text_width = this._ctx.measureText(text).width;
        this._ctx.fillText(text, this._width / 2 - text_width / 2, this._height / 2 + 15);
      },
      /**
       * @param {number} progress
       * @private
       */
      _redraw: function (progress) {
        this._clear();
        this._draw(progress);
      },
      _setHandlers: function () {
        window.addEventListener('scroll', this._onScroll, false);
      },
      _onScroll: function () {
        if (this._isVisible()) {
          this._animate();
        }
      },
      /**
       * @private
       */
      _initialize: function () {
        this._onReady(function () {
          if (this._isVisible()) {
            this._animate();
          } else {
            this._setHandlers();
          }
        });
      this._draw(0);
      }
    };
  /**
   * @param {Object} options
   * @param {function} options.step
   * @param {number} options.duration
   * @param {function} options.complete
   * @param {function} [options.timeFunction]
   * @private
   * @static
   */
  Circle._animate = function (options) {
    var start = Date.now(); // сохранить время начала
      requestAnimationFrame(function tick() {
        var timePassed = Date.now() - start;
        var progress = timePassed / options.duration;
        var timeFunction = options.timeFunction || function (progress) {
          return progress;
        };
        progress = progress > 1 ? 1 : progress;
        options.step(timeFunction(progress));
          if (progress === 1) {
            options.complete();
          } else {
            requestAnimationFrame(tick);
          }
      });
  };
    window.onload = function () {
      var canvases = Array.prototype.slice.call(document.querySelectorAll('.canvas'));
      var circles = [];
      var animateEndCount = 0;
      var onEnd = function () {
        animateEndCount++;
        if (circles[animateEndCount]) {
          circles[animateEndCount].setReady();
        }
      };
      canvases.forEach(function (canvas) {
        circles.push(new Circle(canvas, onEnd));
      });
      circles[0].setReady();
    };
Ответить с цитированием
  #2 (permalink)  
Старый 18.12.2015, 01:32
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,068

Сообщение от walker1232
когда дошло до 5 процентов
Circle._animate = function (options) {
    var start = Date.now(); // сохранить время начала
      requestAnimationFrame(function tick() {
        var timePassed = Date.now() - start;
        var progress = timePassed / options.duration;
        var timeFunction = options.timeFunction || function (progress) {
          return progress;
        };
        progress = progress > 1 ? 1 : progress;
        options.step(timeFunction(progress));
          if(progress !== 1) {
            requestAnimationFrame(tick);
          }
          if (progress > .05 && options.complete) {
            options.complete();
            options.complete = null
          }
      });
  };
Ответить с цитированием
  #3 (permalink)  
Старый 18.12.2015, 01:35
Интересующийся
Отправить личное сообщение для walker1232 Посмотреть профиль Найти все сообщения от walker1232
 
Регистрация: 28.11.2015
Сообщений: 24

Как всегда, безупречно ) спасибо большое ))
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
нужно написать фейк с элементами js в vk totcam Работа 3 27.10.2017 14:42
Доработать простой код на JS Айратиус Элементы интерфейса 4 13.11.2014 09:00
Нужно передать массив из php в JS tuezov52 AJAX и COMET 2 07.11.2011 00:08
Нужно изменить направление JS (прокрутка текста) Axel Общие вопросы Javascript 2 18.04.2009 23:34
Нужно с помощью JS записывать данные в БД d!mm Общие вопросы Javascript 2 01.11.2008 18:36