JavaScript의 Canvas API는 그래픽, 애니메이션 및 기타 시각적 요소를 웹페이지에 직접 그릴 수 있는 수단을 제공합니다. <캔버스> 요소는 개발자가 게임, 데이터 시각화, 맞춤형 그래픽 디자인 등 시각적으로 풍부한 애플리케이션을 만들 수 있는 강력한 도구 세트를 제공합니다.
<캔버스> 요소는 그래픽의 컨테이너 역할을 합니다. 이를 그리려면 JavaScript를 사용하고 해당 2D 렌더링 컨텍스트 또는 3D 그래픽용 WebGL 컨텍스트에 액세스해야 합니다.
<canvas> <hr> <h3> <strong>2. Accessing the Canvas Context</strong> </h3> <p>To draw on the canvas, obtain the rendering context:<br> </p> <pre class="brush:php;toolbar:false">const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); // 2D rendering context
예:
ctx.fillStyle = "blue"; ctx.fillRect(50, 50, 150, 100); ctx.strokeStyle = "red"; ctx.strokeRect(50, 50, 150, 100); ctx.clearRect(70, 70, 50, 50);
beginPath(), moveTo(x, y), lineTo(x, y) 및 closePath()를 사용하세요. .
ctx.beginPath(); ctx.moveTo(100, 100); ctx.lineTo(200, 50); ctx.lineTo(300, 100); ctx.closePath(); ctx.fillStyle = "green"; ctx.fill(); ctx.strokeStyle = "black"; ctx.stroke();
const gradient = ctx.createLinearGradient(0, 0, 200, 0); gradient.addColorStop(0, "blue"); gradient.addColorStop(1, "red"); ctx.fillStyle = gradient; ctx.fillRect(50, 50, 200, 100);
캔버스에 텍스트를 추가하려면 다음 방법을 사용하세요.
ctx.font = "20px Arial"; ctx.fillStyle = "purple"; ctx.fillText("Hello Canvas!", 100, 100); ctx.strokeStyle = "black"; ctx.strokeText("Hello Canvas!", 100, 100);
drawImage() 메소드는 캔버스에 이미지를 표시합니다.
const img = new Image(); img.src = "path-to-image.jpg"; img.onload = () => { ctx.drawImage(img, 50, 50, 200, 100); // (image, x, y, width, height) };
ctx.scale(2, 2); // Doubles the size of shapes ctx.fillRect(10, 10, 50, 50);
ctx.rotate((Math.PI / 180) * 45); // Rotate 45 degrees ctx.fillRect(100, 100, 50, 50);
ctx.translate(50, 50); // Moves the canvas origin ctx.fillRect(0, 0, 50, 50);
부드러운 애니메이션을 만들려면 requestAnimationFrame 함수를 사용하세요.
<canvas> <hr> <h3> <strong>2. Accessing the Canvas Context</strong> </h3> <p>To draw on the canvas, obtain the rendering context:<br> </p> <pre class="brush:php;toolbar:false">const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); // 2D rendering context
캔버스 API는 마우스 클릭, 움직임 등의 사용자 상호작용을 처리할 수 있습니다.
ctx.fillStyle = "blue"; ctx.fillRect(50, 50, 150, 100); ctx.strokeStyle = "red"; ctx.strokeRect(50, 50, 150, 100); ctx.clearRect(70, 70, 50, 50);
캔버스 API는 모든 최신 브라우저에서 지원됩니다. <캔버스>를 지원하지 않는 이전 브라우저에 대한 대체 기능을 포함하는 것이 중요합니다.
JavaScript의 Canvas API는 동적인 대화형 웹 그래픽을 만들기 위한 다목적 도구입니다. 개발자는 그 기능을 마스터함으로써 애니메이션, 게임 및 맞춤형 시각화에 대한 무한한 가능성을 열 수 있습니다.
안녕하세요. 저는 Abhay Singh Kathayat입니다!
저는 프론트엔드와 백엔드 기술 모두에 대한 전문 지식을 갖춘 풀스택 개발자입니다. 저는 효율적이고 확장 가능하며 사용자 친화적인 애플리케이션을 구축하기 위해 다양한 프로그래밍 언어와 프레임워크를 사용하여 작업합니다.
제 비즈니스 이메일(kaashshorts28@gmail.com)로 언제든지 연락주세요.
위 내용은 Canvas API로 창의성 발휘: 동적 웹 그래픽을 위한 종합 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!