Develop/PHP, HTML

[html, javascript] canvas에 이미지 삽입하기

레다솔 2023. 8. 8. 15:39
728x90
반응형

화면에 원이 나타나고 원을 클릭하면 사라지는 기능을 가진 javascript 구문이 있다.

 

여기서 원이 사라지고 원 위치에 이미지가 나타나도록 하면 어떨까?

 

먼저 사진처럼 game/img 폴더에 이미지 3개를 넣었다.

 

원을 클릭하여 원이 사라지게 하는 함수에 다음 구문을 넣었다.

 

// 이미지 src를 배열로 저장
var imageFiles = ["./game/img/image1.jpg", "./game/img/image2.jpg", "./game/img/image3.jpg"];
// 이미지 html요소 생성
var image = document.createElement("img");
// src는 배열에서 랜덤으로 뽑기
image.src = imageFiles[Math.floor(Math.random() * imageFiles.length)];
// 원의 지름만큼 이미지 크기 설정
image.width = radius*2;
image.height = radius*2;
// 이미지가 나타날 위치 설정
image.style.left =moveballons[i].el.style.left;
image.style.bottom = moveballons[i].el.style.bottom;

// 구조체를 만들어 위에서 만든 요소를 구조체 요소에 설정
var imagestruct = {};
imagestruct.width = image.width;
imagestruct.height = image.height;
imagestruct.left = parseInt(image.style.left);
imagestruct.bottom = parseInt(image.style.bottom);
imagestruct.src = image.src;
imagestruct.image = image;

// images 라는 전역변수 배열에 넣기
images.push(imagestruct);

images 는 전역으로 선언한 배열이다.

 

 

그리고 원을 캔버스에 그리는 함수에 다음 구문을 넣는다.

// 만약 원을 클릭하여 이미지가 생성됐다면 이미지를 그림
  if(images.length != 0)
  {
    for(var j = 0; j < images.length; j++)
    {
      ctx.drawImage(images[j].image, images[j].left-radius, images[j].bottom - radius, images[j].width, images[j].height);
    }
  }

 

ctx는 const ctx = canvas.getContext("2d"); 이다.

 

 

drawImage는 ( 이미지 객체, x 좌표[ left ], y좌표[ top ], 이미지 너비, 이미지 높이 ) 의 인자를 가진다.

그리고 원은 다음 함수로 그린다.

ctx.arc(x, y, radius, 0, Math.PI * 2);

 

필자는 x에 left , y에 bottom을 넣었고 원을 그렸는데

 

x, y 좌표에서 radius 만큼의 반지름 길이 만큼 그린다 이다.

 

drawImage 코드에서 left와 bottom에서 radius를 뺀 이유는 빼지 않으면 이미지의 left와 top 좌표가 원 중앙에서 시작하기 때문이다.

 

따라서 이미지의 left와 top을 원 중앙에서 반지름만큼 왼쪽, 반지름만큼 위로 올리는 것 이다.

 

 

위 그림처럼 원이 있을 때 원을 클릭하면

 

원 위치에 그림이 나타난다.

728x90
반응형