DEV의 오프라인 페이지에서 그리기 상호 작용을 만드는 방법
                                            
                                                
                                                
                                                
                                                
                                                
                                                 14924 단어  artshowdevjavascript
                    
Canvas는 JavaScript로 그래픽을 만들기 위한 것입니다. 우리는 이를 사용하여 재미있고 대화형 도구를 만들 수 있습니다. 저는 일반적으로 이와 같은 인터랙티브 아트웍을 만들 때 P5.js 을 사용하여 Canvas API를 사용하기 쉽게 만듭니다. 우리는 오프라인 페이지를 가능한 한 독립적이고 가볍게 만들고 싶었습니다. 그래서 오프라인 페이지는 외부 코드를 사용하지 않습니다.
가장 먼저 해야 할 일은 HTML에
<canvas> 태그를 만드는 것입니다. canvas가 공간을 차지하도록 CSS를 추가해야 합니다. 따라서 높이와 너비를 지정하십시오. 우리가 작업할 몇 가지 시작 CSS로 Codepen 템플릿을 만들었습니다.이제 자바스크립트로 넘어갑니다!
가장 먼저 해야 할 일은 HTML에 이미 있는 캔버스 요소를 선택하여 상호 작용할 수 있도록 하는 것입니다. 또한 캔버스 컨텍스트에 대한 변수를 생성해야 합니다. 그림이 2차원일 뿐이므로 2D 컨텍스트를 사용합니다.
const canvas = document.querySelector('canvas')
const context = canvas.getContext('2d')
또한 이미지가 왜곡되지 않도록 JavaScript에서 캔버스 크기를 설정하려고 합니다.
canvas.setAttribute('width', window.innerWidth)
canvas.setAttribute('height', window.innerHeight)
이제 이벤트 리스너를 추가해야 합니다. 그리기 앱의 경우 다음을 추가하고 싶습니다.
따라서 위의 이벤트에 응답할 세 가지 이벤트 처리 함수가 필요합니다. 사람이 그림을 그리기 시작할 때마다 실행되는
startPaint 함수부터 시작하겠습니다.JavaScript의 다른 요소와 동일한 방식으로 이벤트 리스너를 추가할 수 있습니다.
function startPaint (e) {
}
canvas.addEventListener('mousedown', startPaint)
canvas.addEventListener('touchstart', startPaint)
startPaint 함수가 몇 가지 작업을 수행하기를 원합니다.mousemove 핸들러가 현재 그림을 그릴 때만 작동하도록 현재 그림을 그리는지 여부를 추적하는 변수가 필요합니다. 그리기를 시작할 때마다 true로 설정해야 합니다. 
let x, y, isPainting;
function getCoordinates(event) {
  // check to see if mobile or desktop
  if (["mousedown", "mousemove"].includes(event.type)) {
    // click events
    return [event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop];
  } else {
    // touch coordinates
    return [
      event.touches[0].pageX - canvas.offsetLeft,
      event.touches[0].pageY - canvas.offsetTop
    ];
  }
}
function startPaint(e) {
  // change the old coordinates to the new ones*
  isPainting = true;
  let coordinates = getCoordinates(e);
  x = coordinates[0];
  y = coordinates[1];
}
그런 다음 사람이 그리기 위해 마우스를 움직일 때 처리해야 합니다. 여기서 우리는 다음을 수행해야 합니다.
function drawLine(firstX, firstY, secondX, secondY) {
  // set the attributes of the line
  context.strokeStyle = "black";
  context.lineJoin = "round";
  context.lineWidth = 5;
  context.beginPath();
  context.moveTo(secondX, secondY);
  context.lineTo(firstX, firstY);
  context.closePath();
  // actually draw the path*
  context.stroke();
}
function paint(e) {
  if (isPainting) {
    let [newX, newY] = getCoordinates(e);
    drawLine(x, y, newX, newY);
    // Set x and y to our new coordinates
    x = newX;
    y = newY;
  }
}
canvas.addEventListener("mousemove", paint);
canvas.addEventListener("touchmove", paint);
이제 마우스를 놓을 때 그리기를 중지하기만 하면 됩니다!
function exit() {
  isPainting = false;
}
canvas.addEventListener("mouseup", exit);
canvas.addEventListener("mouseleave", exit);
canvas.addEventListener("touchend", exit);
이제 색상을 변경하고 페이지 크기를 조정할 수 있는 완성된 버전이 있습니다!
저는 특히 사람들이 상호 작용할 수 있는 코드로 예술을 만드는 것을 좋아합니다. 더 자세히 알고 싶다면 이 주제에 대한 몇 가지 게시물이 더 있습니다.
 
    생성 예술 소개
Ali Spittel · 25 '18년 9월 25일 · 6분 읽기
        #art
        #frontend
        #javascript
        #showdev
      
     
    예술을 통해 CSS 배우기
Ali Spittel ・ 2018년 6월 27일 ・ 1분 읽기
        #devlive
        #webdev
        #css
      
    Reference
이 문제에 관하여(DEV의 오프라인 페이지에서 그리기 상호 작용을 만드는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/aspittel/how-to-create-the-drawing-interaction-on-dev-s-offline-page-1mbe텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)