>  Q&A  >  본문

ctx 대체. requestAnimationFrame()을 사용할 때 스트로크 스타일을 사용하세요.

<p>랜딩 페이지의 배경 캔버스로 간단한 임의 동작을 그리려고 하는데 선에 고유한 색상을 지정하는 데 문제가 있습니다. <br /><br /> 영화가 끝난 후 변경해 보았지만 성공하지 못했습니다(색이 혼합된 것처럼 보입니다).


<p><br /></p> <pre class="brush:js;toolbar:false;">const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); //ctx.canvas.width = window.innerWidth; //ctx.canvas.height = window.innerHeight*4; const numSteps = ctx.canvas.width / 2 + 10; const stepSize = 10; const startX = 0; const startY = canvas.height / 2; const timeInterval = 15; var 포인트 = 함수(color_inp){ this.x = startX; this.y = 시작Y; this.color = color_inp; } const 색상 = [ '#FF1493', // 분홍색 '#FF00FF', // 마젠타색 '#800080', // 보라색 '#4B0082', // 인디고 '#0000FF', // 파란색 '#00FFFF', // 청록색 '#00FF00', // 녹색 '#FFFF00', // 노란색 '#FF7F00', // 주황색 '#8B4513' // 새들 브라운 ]; 함수 drawRandomWalk(stPoint, 단계) { ctx.globalAlpha = 0.01; stepCount = 0으로 둡니다. ctx.beginPath(); ctx.StrokeStyle = stPoint.color; ctx.moveTo(stPoint.x, stPoint.y); setTimeout(drawStep, 10); 함수 drawStep() { if (stepCount >= steps) { 반품; } ctx.moveTo(stPoint.x, stPoint.y); const 방향 = Math.random() < 0.5 ? -1 : 1; stPoint.y += stepSize * 방향; stPoint.x = startX + stepCount * 2; ctx.lineTo(stPoint.x, stPoint.y); ctx.lineWidth = 1; ctx.스트로크(); 단계수++; requestAnimationFrame(drawStep); } } for(색상의 상수 색상) { const startPoint = new Point(color); drawRandomWalk(startPoint, numSteps); }</pre> <pre class="brush:html;toolbar:false;"><canvas id="myCanvas" width="600" height="600"></canvas></pre> <p><br /></p>
P粉605385621P粉605385621445일 전464

모든 응답(1)나는 대답할 것이다

  • P粉327903045

    P粉3279030452023-08-02 00:56:35

    문제는 선을 그리는 모든 "펜"이 상태를 공유한다는 것입니다. 즉, 여러 이동/선으로 구성된 긴 경로를 계속해서 그리고 있다는 것입니다.

    글로벌 알파 그라디언트 효과(선을 계속해서 그릴 수 있는 능력에 의존함)를 원한다면 각 펜 그리기를 개별적으로 추적하고 아래와 같이 그려야 합니다.

    포인트 구조는 별로 필요하지 않기 때문에 제거했습니다.


    으아아아 으아아아


    회신하다
    0
  • 취소회신하다