Демонстрация по адресу: https://okazari.github.io/rythm.js/
Библиотека JavaScript, которая делает вашу страницу танцевать.
Установите с помощью NPM:
npm install rythm.jsИли получить от CDN:
https://unpkg.com/rythm.js/
https://cdnjs.cloudflare.com/ajax/libs/rythm.js/2.2.6/rythm.min.js
Импортируйте ритм в вашу страницу:
< script type =" text/javascript " src =" /path/to/rythm.min.js " > </ script >Добавьте один из классов Rythm CSS, чтобы указать, какой элемент будет танцевать:
< div class =" rythm-bass " > </ div >Создайте объект Rythm и дайте ему свой аудио URL, а затем используйте функцию начала:
var rythm = new Rythm ( )
rythm . setMusic ( 'path/to/sample.mp3' )
rythm . start ( ) import Rythm from 'rythm.js'
const rythm = new Rythm ( )
rythm . setMusic ( 'path/to/sample.mp3' )
rythm . start ( ) const rythm = new Rythm ( )
/* The starting scale is the minimum scale your element will take (Scale ratio is startingScale + (pulseRatio * currentPulse)).
* Value in percentage between 0 and 1
* Default: 0.75
*/
rythm . startingScale = value
/* The pulse ratio is be the maximum additional scale your element will take (Scale ratio is startingScale + (pulseRatio * currentPulse)).
* Value in percentage between 0 and 1
* Default: 0.30
*/
rythm . pulseRatio = value
/* The max value history represent the number of passed value that will be stored to evaluate the current pulse.
* Int value, minimum 1
* Default: 100
*/
rythm . maxValueHistory = value
/* Set the music the page will dance to
* @audioUrl: '../example/mysong.mp3'
*/
rythm . setMusic ( audioUrl )
/* Used to collaborate with other players library.
* You can connect Rythm to an audioElement, and then control the audio with your other player
*/
rythm . connectExternalAudioElement ( audioElement )
/* Adjust audio gain
* @value: Number
*/
rythm . setGain ( value )
/* Add your own rythm-class
* @elementClass: Class that you want to link your rythm to
* @danceType: Use any of the built-in effect or give your own function
* @startValue: The starting frequency of your rythm
* @nbValue: The number of frequency of your rythm
* 1024 Frequencies, your rythm will react to the average of your selected frequencies.
* Examples: bass 0-10 ; medium 150-40 ; high 500-100
*/
rythm . addRythm ( elementClass , danceType , startValue , nbValue )
/* Plug your computer microphone to rythm.js.
* This function returns a Promise object that is resolved when the microphone is up.
* Require your website to be run in HTTPS
*/
rythm . plugMicrophone ( ) . then ( function ( ) { ... } )
// Let's dance
rythm . start ( )
/* Stop the party
* @freeze: Set this to true if you want to prevent the elements to reset to their initial position
*/
rythm . stop ( freeze ) Вы можете использовать функцию addRythm , чтобы ваши собственные классы слушали конкретные частоты. Вот как созданы классы оснований:
addRythm('rythm-bass', 'pulse', 0, 10)addRythm('rythm-medium', 'pulse', 150, 40)addRythm('rythm-high', 'pulse', 500, 100) Для получения дополнительной контроля над типами танцев, вы можете дать объект конфигурации в качестве последнего аргумента addRythm :
addRythm ( 'rythm-high' , 'shake' , 500 , 100 , { direction : 'left' , min : 20 , max : 300 } )Вот встроенные танцы и их варианты:
transform: scale() . По умолчанию: 0.75transform: scale() . По умолчанию: 1.25transform: translateY() . По умолчанию: 0transform: translateY() . По умолчанию: 30transform: translateX() . По умолчанию: -15transform: translateX() . По умолчанию: 15left направо влево движется, right для перемещения слева направо. По умолчанию: righttransform: rotate() . По умолчанию: -20transform: rotate() . По умолчанию: 20left направо влево движется, right для перемещения слева направо. По умолчанию: rightopacity . По умолчанию: 0opacity . По умолчанию: 1false (выше пульс, тем более видным будет)[0,0,0][255,255,255][0,0,0][255,255,255]border-radius . По умолчанию: 0border-radius . По умолчанию: 25falsefilter: blur() . По умолчанию: 0filter: blur() . По умолчанию: 8falseup или down . По умолчанию: downright или left . По умолчанию: right20letter-spacing . По умолчанию: 0letter-spacing . По умолчанию: 25false[0,0,0][255,255,255]border-width . По умолчанию: 0border-width . По умолчанию: 5font-width . По умолчанию: 0.8font-width . По умолчанию: 1.2tilt . По умолчанию: 20tilt . По умолчанию: 25false[0,0,0][255,255,255]Чтобы увидеть каждый визуальный эффект, вы можете перейти к демонстрации.
Если вы хотите использовать свой собственный тип танца, вам нужно дать объект в качестве второго аргумента addRythm вместо встроенного танцевального ключа.
Этот объект должен иметь два свойства:
/* The custom function signature is
* @elem: The HTML element target you want to apply your effect to
* @value: The current pulse ratio (percentage between 0 and 1)
* @options: The option object user can give as last argument of addRythm function
*/
const pulse = ( elem , value , options = { } ) => {
const max = options . max || 1.25
const min = options . min || 0.75
const scale = ( max - min ) * value
elem . style . transform = `scale( ${ min + scale } )`
}
/* The reset function signature is
* @elem: The element to reset
*/
const resetPulse = elem => {
elem . style . transform = ''
}
addRythm ( 'my-css-class' , { dance : pulse , reset : resetPulse } , 150 , 40 )Любой запрос на тягу будет оценен. Вы можете начать кодировать в этом проекте после этих шагов:
npm installnpm start в основной папке, чтобы запустить веб -сервер разработкиВ v2.2.x добавить новый тип танца довольно просто:
srcdances Например, вот содержимое файла jump.js :
/* The function signature is
* @elem: The HTML element target you want to apply your effect to
* @value: The current pulse ratio (percentage between 0 and 1)
* @options: The option object user can give as last argument of addRythm function
*/
export default ( elem , value , options = { } ) => {
const max = options . max || 30
const min = options . min || 0
const jump = ( max - min ) * value
elem . style . transform = `translateY( ${ - jump } px)`
}
/* The reset function signature is
* @elem: The element to reset
*/
export const reset = elem => {
elem . style . transform = ''
}Dancer.js : import jump , { reset as resetJump } from './dances/jump.js'
class Dancer {
constructor ( ) {
this . registerDance ( 'jump' , jump , resetJump )
}
}Лицензия: GNU GPL
Автор: @okazaribzh