Как убрать рывки на chrome - PullRequest
1 голос
/ 19 февраля 2020

Я разработчик для сайта моего отца. Вчера я сделал этот пользовательский курсор с ванильными Javascript и CSS: https://codepen.io/ZellRDesign/pen/PoqzgZX

После разработки я протестировал его в своем веб-приложении.

Firefox: нет проблем, код работает очень хорошо, и это довольно здорово.

Вкл. Chrome: здесь у меня возникла первая проблема, иногда пользовательский курсор дергается, и я не знаю, как воспроизвести это ошибка ... Я получил эту ошибку только один раз, но сегодня я делюсь своим кодом с друзьями, и один из них говорит мне: «Смотри, код ошибается»

Пример ошибки: https://i.imgur.com/PW3zCb1.gifv

Итак, у меня есть два вопроса:

как исправить ошибку?

и

как улучшить код, чтобы сделать его лучше?

Спасибо за помощь

const cursor = document.querySelector('.cursor');

document.addEventListener('mousemove', e => {
  cursor.setAttribute("style", "top: " + (e.pageY - 10) + "px; left: " + (e.pageX - 10) + "px;")
})

document.addEventListener('click', () => {
  cursor.classList.add("expand");

  setTimeout(() => {
    cursor.classList.remove("expand");
  }, 500)
})
body {
  margin: 0;
  height: 100vh;
  //cursor: none;
  background: rgb(27, 27, 27);
}

.cursor {
  width: 20px;
  height: 20px;
  border: 1px solid #FAB313;
  ;
  border-radius: 50%;
  position: absolute;
  transition-duration: 200ms;
  transition-timing-function: ease-out;
  animation: cursorAnim .5s infinite alternate;
  pointer-events: none;
}

.cursor::after {
  content: "";
  width: 20px;
  height: 20px;
  position: absolute;
  border: 8px solid #FAB313;
  ;
  border-radius: 50%;
  opacity: .5;
  top: -8px;
  left: -8px;
  animation: cursorAnim2 .5s infinite alternate;
}

@keyframes cursorAnim {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(.7);
  }
}

@keyframes cursorAnim2 {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(.4);
  }
}

@keyframes cursorAnim3 {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(3);
  }
  100% {
    transform: scale(1);
    opacity: 0;
  }
}

.expand {
  animation: cursorAnim3 .5s forwards;
  border: 1px solid #1E2648;
}
<div class="cursor"></div>

Ответы [ 2 ]

0 голосов
/ 19 февраля 2020

Я немного изменил вашу ручку, она, вероятно, работает так, как вам нужно: https://codepen.io/bhoodream/pen/yLNJWEj

Главное, с чем у вас проблемы, это перемещение с top/left. Для таких задач есть transform, в вашем случае вам нужно translate3d. Вот статья о топи c: Анимация движения с помощью translate3d .

0 голосов
/ 19 февраля 2020

Поскольку я не могу воспроизвести проблему на Chrome, я думаю, что вы можете попытаться улучшить общую производительность, используя свойство transform для перемещения курсора (вместо свойств top и left) и свойство will-change.

Поскольку вы уже используете это свойство для импульсной анимации, я вставил элемент-обертку и применил transform там

const cursorW = document.querySelector('.cursor-wrapper');
const cursor = document.querySelector('.cursor');

document.addEventListener('mousemove', e => {
   cursorW.setAttribute("style", 
        "transform: translate("+(e.pageX - 10)+"px, "+(e.pageY - 10)+"px)")
})

document.addEventListener('click', () => {
   cursor.classList.add("expand");

   setTimeout(() => {
      cursor.classList.remove("expand");
   }, 500)
})
body {
    margin: 0;
    height: 100vh;
    //cursor: none;
    background: rgb(27, 27, 27);
}


.cursor-wrapper {
  will-change: transform;
  transition: transform .25s 0s;
}

.cursor {
    width: 20px;
    height: 20px;
    border: 1px solid #FAB313;;
    border-radius: 50%;
    position: absolute;
    transition-duration: 200ms;
    transition-timing-function: ease-out;
    animation: cursorAnim .5s infinite alternate;
    pointer-events: none;
}

.cursor::after {
    content: "";
    width: 20px;
    height: 20px;
    position: absolute;
    border: 8px solid #FAB313;;
    border-radius: 50%;
    opacity: .5;
    top: -8px;
    left: -8px;
    animation: cursorAnim2 .5s infinite alternate;
}

@keyframes cursorAnim {
    from {
        transform: scale(1);
    }
    to {
        transform: scale(.7);
    }
}

@keyframes cursorAnim2 {
    from {
        transform: scale(1);
    }
    to {
        transform: scale(.4);
    }
}

@keyframes cursorAnim3 {
    0% {
        transform: scale(1);
    }
    50% {
        transform: scale(3);
    }
    100% {
        transform: scale(1);
        opacity: 0;
    }
}

.expand {
    animation: cursorAnim3 .5s forwards;
    border: 1px solid #1E2648;
}
<div class="cursor-wrapper">
  <div class="cursor"></div>
</div>

В CSS класс .cursor-wrapper определяется следующим образом:

.cursor-wrapper {
   will-change: transform;
   transition: transform .25s 0s;
}

transform будет Воспользуйтесь ускорением графического процессора, и свойство will-change позволит браузеру узнать, что это свойство будет изменено (я вставил его также в класс .cursor)

Также код JS теперь применяется к классу .cursor-wrapper.

Наконец, смело меняйте скорость анимации.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...