제목을 짓기가 애매해서 대충 지었습니다. 이미지를 계속 뺑뺑이 돌리는 겁니다. MDN에 있는
파노라마 예제를 해보려고 했는데, 코드 분석하기가 싫어서 직접 짜다 보니까 이런게 됐습니다.
테스트삼아 디버깅 정보(맞는 용어인지 모르겠네요)를 화면에 출력하는데, 왼쪽 숫자는 그림의 시작위치(?)입니다.
그림을 일렬로 늘어놓고 왼쪽으로 이 숫자(px)만큼 땡긴거라고 보면 됩니다. 오른쪽 숫자들은 캔버스에 표시되는 그림의 인덱스 번호입니다.
(사진은 '하루나 루나'의 유튜브 썸네일 이미지를 사용했습니다. 문제가 된다면 다른걸로 교체하겠습니다.)
pic1
pic2
pic3
pic4
pic5
<!DOCTYPE html>
<style>
#myCanvas {
border: 3px solid pink;
padding: 3px;
max-width: 100%;
box-sizing: border-box;
}
#myInfo {
display: inline-block;
background: lightgray;
color: gray;
padding: 5px 10px;
min-width: 150px;
}
</style>
<div id="myPics" style="display: none;">
<img src="pics/pic1.jpg">
<img src="pics/pic2.jpg">
<img src="pics/pic3.jpg" >
<img src="pics/pic4.jpg">
<img src="pics/pic5.jpg">
</div>
<p><span id="myInfo">0</span></p>
<canvas id="myCanvas" width="600" height="220"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
var picsObj = {
pics: [/* { elem, width } */],
height: 0,
gap: 0,
length: 0,
pos: 0,
setHeight: function(height) {
this.height = height;
this.gap = 2 * height / 100;
},
addPic(imgElem) {
var width = imgElem.width * this.height / imgElem.height;
this.pics.push({elem: imgElem, width: width});
this.length += width + this.gap;
},
move: function(n) {
this.pos += n;
if (this.pos >= this.length) this.pos -= this.length;
if (this.pos < 0) this.pos += this.length;
},
draw: function(ctx, iList) {
var canvasWidth = ctx.canvas.width;
var x = -this.pos;
var i = 0;
while (x < canvasWidth) {
var pic = this.pics[i];
if (x + pic.width > 0) {
ctx.drawImage(pic.elem, x, 0, pic.width, this.height);
if (iList) iList.push(i);
}
x += pic.width + this.gap;
i = (i + 1 < this.pics.length) ? i + 1 : 0;
}
}
};
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
picsObj.move(2);
var iList = [];
picsObj.draw(ctx, iList);
document.getElementById("myInfo").innerHTML =
Math.floor(picsObj.pos) + " / " + iList.join(", ");
requestAnimationFrame(draw);
}
document.body.onload = function() {
picsObj.setHeight(canvas.height);
for (var img of document.querySelectorAll("#myPics img")) {
picsObj.addPic(img);
}
draw();
}
</script>