새소식

Frontend/HTML&CSS

[HTML] Canvas Tutorial 정리

  • -

기본 형식

function draw() {
  const canvas = document.getElementById('canvas');
  if (canvas.getContext) {
    const ctx = canvas.getContext('2d');
  }
}
draw()

 

모양 만드는 방법

function draw() {
  const canvas = document.getElementById('canvas');
  // browser support 
  if (canvas.getContext) {
    const ctx = canvas.getContext('2d');

    ctx.fillStyle = 'green';
    ctx.fillRect(25, 25, 100, 100);
    ctx.clearRect(45, 45, 60, 60);
    ctx.strokeRect(50, 50, 50, 50);
  }
}
draw();

 

이미지 삽입

function draw() {
  const canvas = document.getElementById('canvas');
  if (canvas.getContext) {
    const ctx = canvas.getContext('2d');
    const img = new Image();

    // 이미지 load event를 마치면 함수 실행
    img.onload = () => {
      ctx.drawImage(img, 0, 0);
    };
    img.src = 'img/apple.png';
  }
}
draw();

 

save and restore

- save: fillStyle (요소 색상) 저장

- restore: 이전에 save()한 요소의 스타일 불러오기

 

function draw() {
  const ctx = document.getElementById("canvas").getContext("2d");

  ctx.fillRect(0, 0, 150, 150); // Draw a rectangle with default settings
  ctx.save(); // Save the default state

  ctx.fillStyle = "#09F"; // Make changes to the settings
  ctx.fillRect(15, 15, 120, 120); // Draw a rectangle with new settings

  ctx.save(); // Save the current state
  ctx.fillStyle = "#FFF"; // Make changes to the settings
  ctx.globalAlpha = 0.5;
  ctx.fillRect(30, 30, 90, 90); // Draw a rectangle with new settings

  ctx.restore(); // Restore previous state
  ctx.fillRect(45, 45, 60, 60); // Draw a rectangle with restored settings

  ctx.restore(); // Restore original state
  ctx.fillRect(60, 60, 30, 30); // Draw a rectangle with restored settings
}

 


 

참고자료

 

Canvas tutorial - Web APIs | MDN

This tutorial describes how to use the <canvas> element to draw 2D graphics, starting with the basics. The examples provided should give you some clear ideas about what you can do with canvas, and will provide code snippets that may get you started in buil

developer.mozilla.org

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.