자바스크립트로 캔버스를 쉽게 사용할 수 있는 라이브러리 Konva를 알게되었다.
Konva는 다음 사진처럼 계층도가 존재한다.
stage는 모든 것을 관리할 루트 객체이며 캔버스는 Layer라고 생각하면된다.
먼저 stage를 정의하기 전에 html을 작성하자.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/konva@9.2.1/konva.js"></script>
</head>
<body>
<div id="stage-parent">
<div id="container"></div>
</div>
<script src="/index.js"></script>
</body>
</html>
container 가 konva stage가 될 것이다.
resize를 이용한 반응형 캔버스를 만들기 위해서는 container가 아닌 stage-parent가 작아지고 커져야 stage가 크기 비율을 유지한다.
이제 js 파일에서 자바스크립트를 작성한다.
var cw = 1280
var ch = 900;
var stage = new Konva.Stage({
container : 'container',
width : cw,
height : ch,
});
var layer = new Konva.Layer();
stage.add(layer);
// zindex는 레이어와 그룹에 있음
// 배경 그림을 그룹으로했고 제일 먼저 만들어진 그룹이 캔버스 맨 뒤로 이동 됨
// 즉 레이어에 먼저 add된 객체가 젤 뒤에 있음
// 그룹 내에서 객체들의 zindex를 조절할 수 있음
var backgroundGroup = new Konva.Group();
layer.add(backgroundGroup);
// 배경 그림 선언 및 소스 지정
var background = new Image();
background.src = './img/image3.jpg';
// 배경 그림 로드되면 콘바 이미지에 넣고 배경 그룹에 추가
background.onload = function(){
var backImage = new Konva.Image({
x:0,
y:0,
image: background,
width:stage.width(),
height:stage.height(),
});
backgroundGroup.add(backImage);
};
zindex는 레이어와 그룹에 있고 제일 먼저 생성되는 객체의 zindex가 제일 작다.
즉 배경그림을 그룹으로 넣고 다른 그림들을 그룹으로 넣지 않아도 배경 그림 그룹의 zindex가 제일 뒤에 있게된다.
다른 그림들을 그리면 그 그림들은 자동으로 배경 그림보다 앞에 그려진다.
konva 객체들은 json 형식으로 생성되므로 객체 선언 및 생성과 초기화를 json 형식으로 진행한다.
콘솔 로그를 찍어보면 이해갈 것 이다.
이 다음에 반응형 페이지를 만들어보자.
function changeWinSize() {
var container = document.querySelector('#stage-parent');
// now we need to fit stage into parent container
var containerWidth = container.offsetWidth;
// but we also make the full scene visible
// so we need to scale all objects on canvas
var scale = containerWidth / cw;
if(cw * scale <= 1280)
{
stage.width(cw * scale);
stage.height(ch * scale);
stage.scale({ x: scale, y: scale });
}
else{
stage.width(1280);
stage.height(900);
stage.scale({ x: 1, y: 1 });
}
}
window.onresize = function (evt) {
console.log("resize");
changeWinSize();
};
공식에서 제공하는 코드를 살짝 변형했다.
https://konvajs.org/docs/sandbox/Responsive_Canvas.html#sidebar
Responsive Canvas Stage Demo
Do you need responsive/adaptive canvas for you desktop and mobile applications?So first of all, there are many way to make your canvas stage “responsive”.And you may need a different behavior for diff
konvajs.org
캔버스 크기에 맞춰 resize되는 크기를 제한해야하기 때문이다.
'Develop > PHP, HTML' 카테고리의 다른 글
[WSL] WSL에서 Vue 개발 서버 실행 후 외부 기기에서 접속하는 방법 (3000번 포트 기준) (0) | 2025.04.14 |
---|---|
[HTML, js, konva] konva 사용할 때 메모리 누수 방지하기 (2) | 2023.10.05 |
[php] 다중 배열을 특정 키 값으로 정렬하기 ( array_multisort ) (0) | 2023.08.31 |
[html, javascript] canvas에 이미지 삽입하기 (0) | 2023.08.08 |
[html, javascript] 동일한 setInterval 반복 호출 막기 (0) | 2023.08.08 |