mousemove

Shin Woohyun·2021년 8월 5일
0

event methods

🎨drawing

  1. 그리기는 mousedown 이벤트부터 시작한다. x,y변수에 mouse pointer를 저장하고, isDrawing을 true로 셋팅한다.
  2. mousemove는 isDrawing이 true일 때, drawLine 함수를 불러서 저장된 x,y변수부터 현재 위치까지 그리게 한다. drawLine 함수의 리턴값을 적용하고 x,y변수에 저장한다.
  3. mouseup하면, 마지막 부분을 그리게 되고, x,y변수에 0을 주고 isDrawing을 false로 셋팅하여 멈춘다.
let isDrawing = false;
let x = 0;
let y = 0;

const myPics = document.getElementById('myPics');
const context = myPics.getContext('2d');

// event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas.
myPics.addEventListener('mousedown', e => {
    x = e.offsetX;
    y = e.offsetY;
    isDrawing = true;
});

myPics.addEventListener('mousemove', e => {
    if(isDrawing === true) {
        drawLine(context, x, y, e.offsetX, e.offsetY);
        x = e.offsetX;
        y = e.offsetY;
    }
});

window.addEventListener('mouseup', e => {
    if(isDrawing === true) {
        drawLine(context, x, y, e.offsetX, e.offsetY);
        x = 0;
        y = 0;
        isDrawing = false;
    }
});

function drawLine (context, x1, y1, x2, y2) {
    context.beginPath();
    context.strokeStyle = 'black';
    context.lineWidth = 1;
    context.moveTo(x1, y1);
    context.lineTo(x2, y2);
    context.stroke();
    context.closePath();
}

https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event

🏝img

강의를 듣다보니 하고 있지만 물론 이런 효과 굉장히 좋아하고 재밌는데 이렇게 하려고 생각하게 된 이유가 궁금한데 물어보기도 애매한.

  1. .page-container > .page-back 부모 자식 관계의 div를 두 개 만든다.
  2. 부모 div는 position: fixed로 화면에 꽉 차게 보여주고, 자식 div는 position:absolute로 20%씩 넘치게 크기를 정한다.
  3. 아래는 main.js
    transform은 GPU를 쓰기 때문에, CPU와 분리가 되서 margin보다 속도측면에서 향상된다고 한다.
const pageContainer = document.querySelector('.page-container');
const pageBack = document.querySelector('.page-back');

// 현재 화면(Viewport)의 크기
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;

pageContainer.addEventListener('mousemove', function(e){
    // mousemove 이벤트 객체의 pageX, pageY가 좌표값
    // moveX, moveY는 중앙이 기준으로 `+ <-x-> -` 보통의 x,y 좌표의 y축 기준 거울상.
    const moveX = ((windowWidth/2) - e.pageX) * 0.1;
    const moveY = ((windowHeight/2) - e.pageY) * 0.1;

    // pageBack.style.marginLeft = `${moveX}px`;
    // pageBack.style.marginTop = `${moveY}px`;
  
    pageBack.style.transform = `translate(${moveX}px, ${moveY}px)`;
})

0개의 댓글