작년에 나는 Temporal 프로젝트에서 Shawn Wang (Swyx)과 협력 할 기회가있었습니다. 목표는 창의적인 요소로 웹 사이트를 향상시키는 것이 었습니다. 디자이너보다 개발자가 많기 때문에 이것은 매혹적인 도전이었습니다. 그러나 디자인 기술을 확장 할 수있는 기회를 수용했습니다.
저의 기여 중 하나는 대화식 별이 많은 배경이었습니다. 여기에서 실제로 볼 수 있습니다.
관점 및 CSS 사용자 정의 속성을 사용한 블록 쿼트 개념. @temporalio에서 창조적 인 자유를 즐기고 있습니다. 기발한 터치 추가! ⚒️ @reactjs && @tailwindcss (사이트는 Nextjs)? @codepen pic.twitter.com/s9xp2trrox를 통해 Codepen 링크
- Jhey ?? ?? (@jh3yy) 2021 년 7 월 2 일
이 디자인의 강점은 재사용 가능한 반응 구성 요소로서 구현하여 높은 구성 가능성을 제공합니다. 별 대신 다른 모양이 필요하십니까? 입자 배치를 정확하게 제어하고 싶습니까? 당신은 완전히 통제하고 있습니다.
이 구성 요소를 구축합시다! 우리는 React, Greensock 및 HTML을 사용합니다<canvas></canvas>
요소. React는 선택 사항이지만이를 사용하면 향후 프로젝트를위한 재사용 가능한 구성 요소가 생성됩니다.
'https://cdn.skypack.dev/react'에서 가져 오는 반응; 'https://cdn.skypack.dev/react-dom'의 import Reactdom; 'https://cdn.skypack.dev/gsap'에서 GSAP 가져 오기; const root_node = document.querySelector ( '#app'); const starscape = () =><h1> 멋진 Thingzzz!</h1> ; const app = () =><starscape></starscape> ; REACTDOM.RENDER (<app></app> , root_node);
먼저, 우리는 a<canvas></canvas>
React의 useEffect
후크 내에서 사용하기위한 기준을 요소하고 잡습니다. React를 사용하지 않으면 참조를 변수에 직접 저장하십시오.
const starscape = () => { const canvasref = react.useref (null); 반품<canvas ref="{canvasRef}"></canvas> ; };
우리는 스타일입니다<canvas></canvas>
뷰포트를 채우고 컨텐츠 뒤에 앉으려면 :
캔버스 { 위치 : 고정; 삽입 : 0; 배경 : #262626; Z- 인덱스 : -1; 높이 : 100VH; 너비 : 100VW; }
우리는 다양한 불투명과 크기의 원을 사용하여 스타 렌더링을 단순화 할 것입니다. a에 원을 그리십시오<canvas></canvas>
컨텍스트를 얻고 arc
함수를 사용하는 것이 포함됩니다. useEffect
후크를 사용하여 중앙에 원 (우리 별)을 렌더링하겠습니다.
const starscape = () => { const canvasref = react.useref (null); const contextref = react.useref (null); React.useeffect (() => { canvasref.current.width = window.innerWidth; canvasref.current.height = window.innerheight; Contextref.current = canvasref.current.getContext ( '2d'); Contextref.current.fillStyle = 'Yellow'; Contextref.current.beginpath (); contextref.current.arc ( Window.innerWidth / 2, // x Window.innerHeight / 2, // y 100, // 반경 0, // 시작 각도 (라디안) Math.pi * 2 // 종료 각도 (라디안) ); contextref.current.fill (); }, []); 반품<canvas ref="{canvasRef}"></canvas> ; };
이것은 노란색 원을 만듭니다. 나머지 코드는이 useEffect
내에 있습니다. 이것이 반응 부분이 선택 사항 인 이유입니다. 다른 프레임 워크에 대해이 코드를 조정할 수 있습니다.
우리는 여러 별을 생성하고 렌더링해야합니다. 캔버스 크기를 포함하여 스타 생성 및 캔버스 설정을 처리하기위한 LOAD
기능을 작성하겠습니다.
const load = () => { const vmin = math.min (Window.InnerHeight, Window.innerWidth); const star_count = math.floor (vmin * densityratio); canvasref.current.width = window.innerWidth; canvasref.current.height = window.innerheight; starsref.current = new Array (star_count) .fill (). map (() => ({{ X : gsap.utils.random (0, window.innerwidth, 1), y : gsap.utils.random (0, window.innerheight, 1), 크기 : gsap.utils.random (1, Sizelimit, 1), 스케일 : 1, alpha : gsap.utils.random (0.1, defaultalpha, 0.1), }); };
각 별은 특성 (x, y 위치, 크기, 스케일, 알파)을 정의하는 특성을 가진 객체입니다. sizeLimit
, defaultAlpha
및 densityRatio
기본값을 가진 별 Starscape
구성 요소로 전달되는 소품입니다.
샘플 스타 객체 :
{ "X": 1252, "Y": 29, "크기": 4, "스케일": 1, "알파": 0.5 }
이 별을 렌더링하기 위해, 우리는 stars
배열 위로 반복하는 RENDER
함수를 만듭니다 arc
const render = () => { contextref.current.clearRect ( 0, 0, canvasref.current.width, canvasref.current.height ); starsref.current.foreach ((star) => { Contextref.current.fillstyle =`hsla (0, 100%, 100%, $ {star.alpha})`; Contextref.current.beginpath (); Contextref.current.arc (star.x, star.y, star.size / 2, 0, math.pi * 2); contextref.current.fill (); }); };
clearRect
함수는 렌더링 전에 캔버스를 지우므로 애니메이션에 중요합니다.
완전한 Starscape
구성 요소 (아직 상호 작용이없는)는 다음과 같습니다.
스타 스케이프 구성 요소 (상호 작용없이)
const starscape = ({densityratio = 0.5, sizelimit = 5, defaultalpha = 0.5}) => { const canvasref = react.useref (null); const contextref = react.useref (null); const starsref = react.useref (null); React.useeffect (() => { Contextref.current = canvasref.current.getContext ( '2d'); const load = () => { const vmin = math.min (Window.InnerHeight, Window.innerWidth); const star_count = math.floor (vmin * densityratio); canvasref.current.width = window.innerWidth; canvasref.current.height = window.innerheight; starsref.current = new Array (star_count) .fill (). map (() => ({{ X : gsap.utils.random (0, window.innerwidth, 1), y : gsap.utils.random (0, window.innerheight, 1), 크기 : gsap.utils.random (1, Sizelimit, 1), 스케일 : 1, alpha : gsap.utils.random (0.1, defaultalpha, 0.1), }); }; const render = () => { Contextref.current.clearRect (0, 0, CanvasRef.current.width, canvasref.current.height); starsref.current.foreach ((star) => { Contextref.current.fillstyle =`hsla (0, 100%, 100%, $ {star.alpha})`; Contextref.current.beginpath (); Contextref.current.arc (star.x, star.y, star.size / 2, 0, math.pi * 2); contextref.current.fill (); }); }; const run = () => { 짐(); 세우다(); }; 달리다(); window.addeventListener ( 'resize', run); return () => { window.removeEventListener ( 'resize', run); }; }, []); 반품<canvas ref="{canvasRef}"></canvas> ; };
데모로 소품을 실험하여 그 효과를 확인하십시오. 뷰포트 크기 조정을 처리하기 위해 LOAD
및 RENDER
크기 조정 (여기에서 최적화를 위해 Defouncing, 여기에서는 생략).
이제 배경 대화 형을 만들어 봅시다. 포인터가 움직이면 커서 근처의 별이 밝아지고 확장됩니다.
포인터와 각 스타 사이의 거리를 계산하기 위해 UPDATE
기능을 추가 한 다음 Greensock의 mapRange
유틸리티를 사용하여 Star의 스케일과 알파를 트윈 트위링합니다. 또한 스케일링 동작을 제어하기 위해 scaleLimit
및 proximityRatio
소품을 추가합니다.
const update = ({x, y}) => { starsref.current.foreach ((star) => { const 거리 = Math.sqrt (math.pow (star.x -x, 2) math.pow (star.y -y, 2)); gsap.to (star, { 스케일 : scalemapperref.current (math.min (거리, vminref.current * proximityRatio)), 알파 : alphamapperref.current (math.min (거리, vminref.current * proximityRatio)), }); }); };
업데이트를 렌더링하기 위해 gsap.ticker
( requestAnimationFrame
의 좋은 대안)를 사용하여 시세에 RENDER
추가하고 정리에서 제거합니다. 초당 프레임 (FPS)을 24로 설정합니다. RENDER
함수는 이제 ARC를 그리울 때 star.scale
값을 사용합니다.
짐(); gsap.ticker.add (render); gsap.ticker.fps (24); window.addeventListener ( 'resize', load); document.addeventListener ( 'pointermove', 업데이트); return () => { window.removeEventListener ( 'Resize', Load); document.removeeventListener ( 'pointermove', update); gsap.ticker.remove (render); };
이제 마우스를 움직일 때 별이 반응합니다!
마우스가 캔버스를 떠나는 경우를 처리하기 위해, 우리는 별을 원래 상태로 돌려 보내는 pointerleave
이벤트 리스너를 추가합니다.
const exit = () => { gsap.to (starsref.current, {scale : 1, alpha : defaultalpha}); }; // ... 이벤트 청취자 ... document.addeventListener ( 'pointerleave', exit); return () => { // ... 정리 ... document.removeEventListener ( 'pointerleave', exit); gsap.ticker.remove (render); };
코나미 코드 부활절 달걀을 추가합시다. 코드가 입력되면 키보드 이벤트를 듣고 애니메이션을 트리거합니다.
const konami_code = '화살표, 화살표, 화살표 다운, 화살표 다운, 화살표, 화살표, 화살표, 화살표, keyb, keya'; const coderef = react.useref ([]); React.useeffect (() => { const handleCode = (e) => { coderef.current = [... coderef.current, e.code] .slice (coderef.current.length> 9? coderef.current.length -9 : 0); if (coderef.current.join ( ','). tolowercase () === konami_code.tolowercase ()) { // 부활절 달걀 애니메이션 트리거 } }; window.addeventListener ( 'keyup', handleCode); return () => { window.removeEventListener ( 'keyup', handleCode); }; }, []);
Konami 코드 이스터 에그를 사용한 완전하고 대화식 Starscape
구성 요소는 매우 길고 간결하게 생략되었습니다. 그러나 위에서 설명한 원칙은 React, Greensock 및 HTML을 사용하여 완벽하게 기능적이고 사용자 정의 가능한 대화식 Starry 배경을 만드는 방법을 보여줍니다.<canvas></canvas>
. 부활절 달걀 애니메이션에는 별 속성을 애니메이션하기 위해 gsap.timeline
을 만드는 것이 포함됩니다.
이 예제는 자신만의 맞춤형 배경을 만드는 데 필요한 기술을 보여줍니다. 배경이 사이트의 콘텐츠와 어떻게 상호 작용하는지 고려해야합니다. 다양한 모양, 색상 및 애니메이션으로 실험하여 독특하고 매력적인 비주얼을 만듭니다.
위 내용은 콘텐츠를위한 대화식 별이 빛나는 배경의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!