2014-02-20 2 views
0

이 페이지가 열리면 오렌지색과 황갈색의 두 가지 모양이 나타납니다. 현재 오렌지색 사각형을 클릭하면 녹색 사각형이 나타납니다. 주황색 직사각형 바깥에서 마우스를 클릭하면 녹색 선이 사라집니다. 이것은 내가 ctx.clear()를 시도한 다른 곳에서 이루어질 것입니다;캔버스에서 모양 지우기

<!DOCTYPE html> 

<html lang="en"> 
<head> 
    <meta charset="UTF-8" /> 
    <title>testclick</title> 
    <script> 

    function init() { 

     var canvas = document.getElementById("canvas"); 
     var ctx = canvas.getContext("2d"); 

     tan(ctx); 

     orange(ctx); 

     canvas.onclick = function (e) 
     { 
      var canvas = e.target; 
      var ctx = canvas.getContext('2d'); 

      // This gets the mouse coordinates (relative to the canvas) 
      var mouseX = e.clientX - canvas.getBoundingClientRect().left; 
      var mouseY = e.clientY - canvas.getBoundingClientRect().top; 


      // Replay the rectangle path (no need to fill() it) and test it 
      ctx.beginPath(); 
      ctx.moveTo(663.3, 254.3); 
      ctx.lineTo(516.0, 254.3); 
      ctx.lineTo(516.0, 176.7); 
      ctx.lineTo(663.3, 176.7); 
      ctx.lineTo(663.3, 254.3); 

      if (ctx.isPointInPath(mouseX, mouseY)) { 
       ctx.save(); 
       ctx.beginPath(); 
       ctx.moveTo(417.3, 320.7); 
       ctx.lineTo(113.3, 320.7); 
       ctx.lineTo(113.3, 0.0); 
       ctx.lineTo(417.3, 0.0); 
       ctx.lineTo(417.3, 320.7); 
       ctx.closePath(); 
       ctx.fillStyle = "rgb(60, 127, 60)"; 
       ctx.fill(); 
      } else { 
       ctx.clear(); 
       ctx.moveTo(417.3, 320.7); 
       ctx.lineTo(113.3, 320.7); 
       ctx.lineTo(113.3, 0.0); 
       ctx.lineTo(417.3, 0.0); 
       ctx.lineTo(417.3, 320.7); 
      } 

     } 
    } 

    function tan(ctx) { 

     // tan/Path 
     ctx.save(); 
     ctx.beginPath(); 
     ctx.moveTo(393.3, 422.7); 
     ctx.lineTo(0.0, 422.7); 
     ctx.lineTo(0.0, 52.7); 
     ctx.lineTo(393.3, 52.7); 
     ctx.lineTo(393.3, 422.7); 
     ctx.closePath(); 
     ctx.fillStyle = "rgb(255, 238, 191)"; 
     ctx.fill(); 
     ctx.restore(); 
    } 

    function orange(ctx) { 

     // orange/Path 
     ctx.save(); 
     ctx.beginPath(); 
     ctx.moveTo(663.3, 254.3); 
     ctx.lineTo(516.0, 254.3); 
     ctx.lineTo(516.0, 176.7); 
     ctx.lineTo(663.3, 176.7); 
     ctx.lineTo(663.3, 254.3); 
     ctx.closePath(); 
     ctx.fillStyle = "rgb(240, 89, 41)"; 
     ctx.fill(); 
     ctx.restore(); 
    } 


    </script> 
</head> 
<body onload="init()"> 
    <canvas id="canvas" width="664" height="423"></canvas> 
</body> 
</html> 

답변

0

문맥에 더 clear() 방법이 없습니다. 사용해보기 :

ctx.clearRect(x, y, width, height); 
관련 문제