Coding/JavsScript 삽질기2019. 12. 25. 23:49

소개 https://chobocho.tistory.com/2461396
실행하기 http://www.chobocho.com/javascript/painter.html
전체 소스코드 https://github.com/chobocho/painter

 

chobocho/painter

Painter written html5. Contribute to chobocho/painter development by creating an account on GitHub.

github.com

 

7.1 Refactoring

선, 원등을 그릴때, 반복되는 코드를 preprocessMouseUp(), postprocessMouseUp() 으로 묶습니다.

function circleMouseMove(event) {
  if (!painter.isDraw()) {
    return;
  }
  var currentPos = getMousePosition(event);
  cvs.beginPath();
  // Need a delay
  cvs.clearRect(0, 0, canvas.width, canvas.height);
  cvs.drawImage(bufCanvas, 0, 0);

  cvs.strokeStyle = painter.getColor();

  var circle = {
    X: Math.round((painter.shape.point.x + currentPos.X) / 2),
    Y: Math.round((painter.shape.point.y + currentPos.Y) / 2),
    R: Math.round(Math.abs(currentPos.Y - painter.shape.point.y) / 2)
  };
  cvs.arc(circle.X, circle.Y, circle.R, 0, Math.PI * 2);
  cvs.closePath();
  cvs.stroke();
}

위의 코드를 아래와 같이 수정하였습니다. 기존 함수 내부를 preprocess()와 postprocess()로 나누어서 묶은 것입니다.

Shape.prototype.preprocessMouseUp = function() {
  bufCtx.beginPath();
  bufCtx.strokeStyle = painter.getColor();
}

Shape.prototype.postprocessMouseUp = function() {
  bufCtx.closePath();
  bufCtx.stroke();

  cvs.clearRect(0, 0, canvas.width, canvas.height);
  cvs.drawImage(bufCanvas, 0, 0);

  this.setDrawMode(false);
}

function circleMouseMove(event) {
  if (!painter.isDraw()) {
    return;
  }
  
  painter.preprocessMouseMove();
  
  var currentPos = getMousePosition(event);
  var circle = {
    X: Math.round((painter.shape.point.x + currentPos.X) / 2),
    Y: Math.round((painter.shape.point.y + currentPos.Y) / 2),
    R: Math.round(Math.abs(currentPos.Y - painter.shape.point.y) / 2)
  };
  cvs.arc(circle.X, circle.Y, circle.R, 0, Math.PI * 2);
  
  painter.postprocessMouseMove();
}

 

7.2 나머지 도형 구현

직선, 원과 같이 삼각형, 직사각형에 대해서도 mouseDown, mouseMove, mouseUp에 대한 이벤트를 정의하고

painter 객체에 추가해 줍니다.

 

여기까지의 참고 자료는 아래 링크를 참고 하시면 됩니다.

https://github.com/chobocho/painter/tree/master/doc/tutorial/007

Posted by chobocho