728x90

Javascript에서 SVG를 이용해서 바둑판과 바둑알을 그려보자.

 

※ 소스

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>go</title>
  <style>
    #go2 {
      width: 600px;
      height: 600px;
      background-color: burlywood;
    }
  </style>
</head>
<body>
  <button onclick="initGo(go3)">초기화</button>
  <div id="go1" onclick="clkGo()"></div>
  <script>
    let arr = [];
    let pos = [];

    function initGo(tag) {
      pos = [];
      for(let y = 0; y < 19; y++){
        arr[y] = [];
        for(let x = 0; x < 19; x++)
          arr[y][x] = 0;
      }
      tag.innerHTML ="";
    }
    function clkGo() {
      let n = go2.clientWidth / 20;
      let x = Math.ceil((event.offsetX - n*1.5) / n);
      let y = Math.ceil((event.offsetY - n*1.5) / n);

      if (x < 0 || x > 18 || y < 0 || y > 18 || arr[y][x] != 0) {
        alert("돌을 놓을 수 없습니다.");
        return;
      }
      arr[y][x] = ((pos.length % 2) == 0) ? 1 : -1;
      pos.push([x,y]);
      fill = (arr[y][x] == -1) ? 'fill="#FFF"' : "";
      go3.innerHTML +=`<circle cx="${x*10}" cy="${y*10}" r="4.9" ${fill} />`;
    }

    let borad = `<svg id="go2" viewBox="-10 -10 200 200" stroke-width="1" stroke="black">
      <rect x="0" y="0" width="180" height="180" fill="none" />`;
      for (let i = 1; i < 18; i+=1) {
      let n = i * 10;
      borad += `<line x1="0" y1="${n}" x2="180" y2="${n}"/>`;
      borad += `<line x1="${n}" y1="0" x2="${n}" y2="180" />`;
      if (i == 3 || i == 9 || i == 15) {
        for(let x of [3, 9, 15]) {
          borad += `<circle cx="${n}" cy="${x*10}" r="1" />`;
        }
      }
    }

    borad += `<g id="go3" viewBox="-10 -10 200 200" stroke-width="0"></g></svg>`;
    go1.innerHTML = borad;
    initGo(go3);
  </script>
</body>
</html>

 

※실행화면

 

728x90
반응형

+ Recent posts