<html />const image = document.getElementById('container-img'); const container = document.getElementById('img-container'); let moveInterval; let keysPressed = {}; //이미지 스케일변경 var scaleFactor = 3; var currentWidth = image.clientWidth; var newWidth = currentWidth * scaleFactor; image.style.width = newWidth + 'px'; //실행함수 function moveImage() { let xPos = image.offsetLeft; let yPos = image.offsetTop; let imgwidth = image.offsetLeft; let imgheight = image.offsetTop; //else if로 구분하면 대각선 이동이 안됨 if (keysPressed.ArrowUp) { yPos += 1; } if (keysPressed.ArrowDown) { if (imgheight <= (image.clientHeight - container.clientHeight) * -1) { return; } yPos -= 1; } if (keysPressed.ArrowLeft) { xPos += 1; } if (keysPressed.ArrowRight) { if (imgwidth <= (image.clientWidth - container.clientWidth) * -1) { return; } xPos -= 1; } //제어 if (imgwidth + xPos > 0 || imgheight + yPos > 0) { //log //console.log(xPos); return; } image.style.left = xPos + 'px'; image.style.top = yPos + 'px'; //log //console.log(imgwidth); //console.log(image.style.left + image.style.top); } document.addEventListener('keydown', function (event) { keysPressed[event.key] = true; //키가 눌렸을 때 clearInterval(moveInterval); moveInterval = setInterval(() => { moveImage(); },5); }); document.addEventListener('keyup', function (event) { keysPressed[event.key] = false; //키가 떼어졌을 때 if ( !keysPressed.ArrowUp && !keysPressed.ArrowDown && !keysPressed.ArrowLeft && !keysPressed.ArrowRight ) { clearInterval(moveInterval); } });
<css />
#img-container {
position: relative;
border: 1px solid black;
width: 1020px;
height: 580px;
overflow: hidden;
/*pointer-events: none;*/
pointer-events: visiblePainted;
}
#container-img {
position: absolute;
top: 0;
left: 0;
cursor: move;
}
<html />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Drag Example</title>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<div id="img-container">
<img id="container-img" src="img/test3d.png" />
</div>
<script src="js/script.js"></script>
</body>
</html>
'JavaScript' 카테고리의 다른 글
[js] img animation(2) - 방향키 단순이동, 제어x (0) | 2023.05.02 |
---|---|
[js] img animation(1) - 대각선 이동 (0) | 2023.05.02 |