清除画布中的形状

时间:2014-02-20 16:06:08

标签: javascript html canvas

当此页面打开时,有两种形状:一个橙色和一个棕褐色矩形。现在,当单击橙色矩形时,会出现一个新的绿色矩形。当鼠标在橙色矩形之外被点击时,我希望绿色的鼠标消失。这将在我尝试过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>

1 个答案:

答案 0 :(得分:0)

上下文中没有clear()方法。试试:

ctx.clearRect(x, y, width, height);