# 캔버스 이동·확대 (Pan & Zoom)

지도 위의 한 지점을 확대하고 드래그해 주변 장소를 탐색합니다.

## 체험 방법

지도를 끌어 이동하고 확대·축소한 뒤 ‘처음 위치’로 돌아오세요.

## 재현 기준

한 손가락은 지도 이동, 두 손가락은 중심을 유지하며 확대합니다. 휠은 포인터 위치를 기준으로 1~4배 범위에서 확대·축소합니다. 방향 버튼과 키보드로도 이동할 수 있습니다.

## 기기별 조작

- iOS · 한 손가락으로 이동하고 두 손가락으로 확대하세요. 아래 조작 버튼도 사용할 수 있습니다.
- Android · 한 손가락으로 이동하고 두 손가락으로 확대하세요. 아래 조작 버튼도 사용할 수 있습니다.
- PC · 지도를 끌어 이동하고 휠로 확대하세요. 지도에 초점을 두고 방향키와 +·−로도 움직일 수 있습니다.

## 적용할 때

지도나 넓은 도면을 화면 안에서 움직여 살펴볼 때.

## 그대로 보낼 요청

> 큰 도면을 포인터 중심으로 확대하고 끌어서 이동하며 원래 위치로 복원하게 해줘.

## 참고한 동작

[Leaflet · Map interaction options](https://leafletjs.com/reference.html#map-dragging)

## 독립 실행 코드

아래 전체 코드를 HTML로 저장해 브라우저에서 엽니다.

```html
<!doctype html>
<html lang="ko"><head><script>if(new URLSearchParams(location.search).get('reduce')==='1')document.documentElement.classList.add('motion-reduced');</script><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>캔버스 이동·확대 · Motion Lab</title>
<style>
*{box-sizing:border-box}body{margin:0;font-family:system-ui,-apple-system,"Malgun Gothic",sans-serif;word-break:keep-all}button,input{font:inherit}button{cursor:pointer}button:focus-visible,input:focus-visible,[tabindex]:focus-visible{outline:3px solid #ef7c30;outline-offset:2px}button:disabled{cursor:default}button{touch-action:manipulation}.sr-only{position:absolute;inline-size:1px;block-size:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
body{min-height:100svh;display:grid;place-items:center;padding:15px;background:#d9ded4;color:#1d332d}
main{width:min(100%,760px)}header{display:flex;align-items:baseline;justify-content:space-between;gap:6px;margin:0 0 10px}h1{margin:0;font-size:clamp(21px,4vw,32px);letter-spacing:-.065em}header em{font:italic 16px Georgia,serif}
#map{height:clamp(208px,60svh,340px);width:100%;position:relative;overflow:hidden;border:1px solid #798d80;touch-action:none;cursor:grab;background:#e5dfb9}#map:active{cursor:grabbing}#map canvas{display:block;width:100%;height:100%}.north{position:absolute;top:8px;right:9px;background:#f4eedf;border:1px solid #657366;color:#27392e;padding:4px 6px;font:700 12px/1 monospace;pointer-events:none}
footer{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-top:6px}.group{display:flex;align-items:center;border:1px solid #a3ada0;background:#edf0e5}.group button{min-width:42px;min-height:44px;border:none;background:transparent;color:#273c32;font-weight:650}.group button:hover{background:#d1ddcc}.group button:disabled{opacity:.45}.group output{font:600 12px monospace;min-width:42px;text-align:center}#reset{border:0;border-bottom:1px solid #738271;color:#293e33;min-height:44px;background:transparent;font-size:13px;margin-left:auto}
@media(max-width:490px){body{padding:10px}header em{font-size:13px}footer{gap:3px}.group button{min-width:34px}.group output{min-width:36px}#reset{font-size:12px;padding:0 3px}}
@media(max-width:360px){footer{justify-content:space-between}#reset{margin-left:0}header em{display:none}.group button{min-width:28px}}
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation-duration:.001ms!important;transition-duration:.001ms!important;scroll-behavior:auto!important}}.motion-reduced *,.motion-reduced *::before,.motion-reduced *::after{animation-duration:.001ms!important;transition-duration:.001ms!important;scroll-behavior:auto!important}
</style></head><body>
<main><header><h1>물안길 판화 지도</h1><em lang="en">Riverside Atlas</em></header><div id="map" tabindex="0" role="region" aria-label="물안길 지도. 방향키로 이동하고 더하기·빼기로 확대 또는 축소합니다."><canvas role="img" aria-label="물안길 강과 강변의 우체국, 공방, 시장 및 다리 지도"></canvas><span class="north" aria-hidden="true">↑ N</span></div>
<footer><div class="group" aria-label="배율"><button id="minus" type="button" aria-label="축소">−</button><output id="scale" aria-label="현재 배율">100%</output><button id="plus" type="button" aria-label="확대">＋</button></div><div class="group" aria-label="지도 이동"><button data-pan="left" type="button" aria-label="서쪽으로 이동">←</button><button data-pan="up" type="button" aria-label="북쪽으로 이동">↑</button><button data-pan="down" type="button" aria-label="남쪽으로 이동">↓</button><button data-pan="right" type="button" aria-label="동쪽으로 이동">→</button></div><button id="reset" type="button">처음 위치</button></footer></main>
<script>
const map=document.querySelector('#map'),canvas=map.querySelector('canvas'),ctx=canvas.getContext('2d');
const world={w:1200,h:850}, paths=new Map();
let center={x:590,y:421},zoom=1,w=0,h=0,base=1;
function polygon(points,fill,outline){
  ctx.beginPath();points.forEach(([x,y],i)=>{if(i)ctx.lineTo(x,y);else ctx.moveTo(x,y);});ctx.closePath();ctx.fillStyle=fill;ctx.fill();
  if(outline){ctx.strokeStyle=outline;ctx.lineWidth=1.3;ctx.stroke();}
}
function drawAtlas(){
  ctx.fillStyle='#e6dfbd';ctx.fillRect(0,0,1200,850);
  ctx.save();ctx.translate(590,420);ctx.rotate(-.19);
  const blocks=['#ced0ac','#cac1a0','#dccead','#e1c7a4'];
  for(let j=-8;j<=8;j++)for(let i=-9;i<=9;i++){
    const x=i*76,y=j*57,k=(i*13+j*11+340)%9;
    if(k===0){ctx.fillStyle='#9caf8a';ctx.fillRect(x+4,y+4,67,47);
      ctx.fillStyle='#6f926e';for(let t=0;t<7;t++){ctx.beginPath();ctx.arc(x+11+t*8,y+22+Math.sin(t*2)*8,4,0,Math.PI*2);ctx.fill();}continue;}
    ctx.fillStyle=blocks[(i*i+j*j)%4];ctx.fillRect(x+2,y+3,69,50);
    for(let b=0;b<4;b++){const bx=x+6+(b%2)*32,by=y+7+Math.floor(b/2)*22;ctx.fillStyle='#aa9c7e';ctx.fillRect(bx,by,20+(b+k)%6,14);ctx.fillStyle='#d8c5a3';ctx.fillRect(bx+1,by+1,17+(b+k)%6,11);}
  }
  ctx.restore();
  const river=new Path2D('M-70 671 C140 550 216 679 369 554 S555 308 742 341 S893 543 1270 155');
  ctx.lineCap='round';ctx.strokeStyle='#9ca993';ctx.lineWidth=122;ctx.stroke(river);ctx.strokeStyle='#75a6a3';ctx.lineWidth=109;ctx.stroke(river);ctx.strokeStyle='#93beb3';ctx.lineWidth=99;ctx.stroke(river);
  ctx.save();ctx.translate(0,4);ctx.strokeStyle='#719e97';ctx.setLineDash([8,10]);ctx.lineWidth=1.1;ctx.stroke(river);ctx.restore();
  for(const [x,y,a] of [[386,527,.55],[655,347,-.22],[917,402,-.62]]){
    ctx.save();ctx.translate(x,y);ctx.rotate(a);ctx.fillStyle='#4a6154';ctx.fillRect(-8,-73,16,146);ctx.fillStyle='#f8efd3';ctx.fillRect(-5,-73,10,146);ctx.restore();
  }
  const rail=new Path2D('M-10 195 Q235 112 417 208 T802 202 T1220 126');
  ctx.lineWidth=3;ctx.strokeStyle='#7d755e';ctx.stroke(rail);ctx.save();ctx.setLineDash([1.5,7]);ctx.lineWidth=7;ctx.stroke(rail);ctx.restore();
  polygon([[506,458],[553,442],[573,477],[520,492]],'#b96e4c','#794c37');
  polygon([[708,235],[749,225],[763,255],[720,268]],'#b96e4c','#794c37');
  const labels=[[540,484,'판화 공방'],[474,299,'종이 시장'],[805,471,'남쪽 우체국'],[351,618,'갈대 정원'],[701,246,'기록 보관소']];
  ctx.font='bold 14px system-ui';ctx.textAlign='center';ctx.textBaseline='middle';
  for(const [x,y,title] of labels){ctx.fillStyle='#314b3f';ctx.beginPath();ctx.arc(x,y,6,0,Math.PI*2);ctx.fill();ctx.lineJoin='round';ctx.lineWidth=5;ctx.strokeStyle='#f4eedb';ctx.strokeText(title,x,y-17);ctx.fillText(title,x,y-17);}
  ctx.save();ctx.translate(622,366);ctx.rotate(-.43);ctx.font='italic 24px Georgia';ctx.fillStyle='#215852';ctx.fillText('Mulan River',0,0);ctx.restore();
}
function render(){
  const rect=map.getBoundingClientRect(),dpr=Math.min(devicePixelRatio||1,2);w=map.clientWidth;h=map.clientHeight;if(!w||!h)return;
  base=Math.max(w/708,h/450);const factor=base*zoom,rx=w/(2*factor),ry=h/(2*factor);
  center.x=Math.max(rx,Math.min(world.w-rx,center.x));center.y=Math.max(ry,Math.min(world.h-ry,center.y));
  const pw=Math.round(w*dpr),ph=Math.round(h*dpr);if(canvas.width!==pw||canvas.height!==ph){canvas.width=pw;canvas.height=ph;}
  ctx.setTransform(dpr*factor,0,0,dpr*factor,dpr*(w/2-center.x*factor),dpr*(h/2-center.y*factor));drawAtlas();
  document.querySelector('#scale').textContent=Math.round(zoom*100)+'%';
  document.querySelector('#minus').disabled=zoom<=1;document.querySelector('#plus').disabled=zoom>=4;
}
function offset(e){const rect=map.getBoundingClientRect();return{x:e.clientX-rect.left-map.clientLeft,y:e.clientY-rect.top-map.clientTop};}
function worldAt(p){return{x:center.x+(p.x-w/2)/(base*zoom),y:center.y+(p.y-h/2)/(base*zoom)};}
function scaleAt(next,p={x:w/2,y:h/2},at=worldAt(p)){
  zoom=Math.max(1,Math.min(4,next));center={x:at.x-(p.x-w/2)/(base*zoom),y:at.y-(p.y-h/2)/(base*zoom)};render();
}
function pan(direction){const delta={left:[-1,0],right:[1,0],up:[0,-1],down:[0,1]}[direction];center.x+=delta[0]*56/(base*zoom);center.y+=delta[1]*56/(base*zoom);render();}
function reset(){center={x:590,y:421};zoom=1;render();}
document.querySelector('#plus').onclick=()=>scaleAt(zoom*1.4);document.querySelector('#minus').onclick=()=>scaleAt(zoom/1.4);
document.querySelectorAll('[data-pan]').forEach(b=>b.onclick=()=>pan(b.dataset.pan));document.querySelector('#reset').onclick=reset;
map.addEventListener('wheel',e=>{e.preventDefault();const unit=e.deltaMode===1?16:e.deltaMode===2?h:1;scaleAt(zoom*Math.exp(-Math.max(-250,Math.min(250,e.deltaY*unit))*.002),offset(e));},{passive:false});
map.addEventListener('keydown',e=>{const dirs={ArrowLeft:'left',ArrowRight:'right',ArrowUp:'up',ArrowDown:'down'};
  if(dirs[e.key]){e.preventDefault();pan(dirs[e.key]);}else if(['+','=','-','Home'].includes(e.key)){e.preventDefault();if(e.key==='Home')reset();else scaleAt(zoom*(e.key==='-'?1/1.4:1.4));}
});
map.addEventListener('pointerdown',e=>{if(e.button!==0)return;paths.set(e.pointerId,offset(e));map.setPointerCapture(e.pointerId);map.focus({preventScroll:true});});
const mid=(a,b)=>({x:(a.x+b.x)/2,y:(a.y+b.y)/2}),dist=(a,b)=>Math.hypot(a.x-b.x,a.y-b.y);
map.addEventListener('pointermove',e=>{
  if(!paths.has(e.pointerId))return;
  const before=[...paths.values()],old=paths.get(e.pointerId),p=offset(e);paths.set(e.pointerId,p);
  const after=[...paths.values()];
  if(after.length===1){center.x-=(p.x-old.x)/(base*zoom);center.y-=(p.y-old.y)/(base*zoom);render();}
  else if(after.length===2){const oldDistance=dist(before[0],before[1]);if(oldDistance>=2)scaleAt(zoom*dist(after[0],after[1])/oldDistance,mid(after[0],after[1]),worldAt(mid(before[0],before[1])));}
});
for(const type of ['pointerup','pointercancel','lostpointercapture'])map.addEventListener(type,e=>paths.delete(e.pointerId));
new ResizeObserver(render).observe(map);render();
</script></body></html>
```

