Javascript画布没有被清理

时间:2014-08-16 01:05:20

标签: javascript canvas rotation

由于此代码,我必须寻求帮助:

    <head>
     <title>Rectangles</title>

      <style> 
         body {
        background: #dddddd;
     }

     #canvas {
        background: #eeeeee;
        border: thin solid #aaaaaa;
     }
  </style>
</head>

<body>
<canvas id='canvas' width="578" height="200">
  Canvas not supported
</canvas>
<br>
<button type="button"id="disminuir" onclick="disminuir()">Girar CCW</button> 
<button type="button"id="aumentar" onclick="aumentar()">Girar CW</button> 

<script src='script.js'></script>
</body>
</html>

这个javascript:

嗯,实际上它并没有表现得好主要是因为每次重绘盒子时,画布都没有被清除......

var context;
var rectWidth = 64;
var rectHeight = 64;
var rotation;
rotation=0;

var canvas = document.getElementById("canvas");  
context = canvas.getContext("2d");
context.translate(canvas.width / 2, canvas.height / 2);


draw();


   function draw() { 

            context.clearRect(0, 0, canvas.width, canvas.height);    
            context.strokeRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
            context.rotate(rotation * 1 * Math.PI / 180);


    }     

function aumentar()
{
 rotation=rotation+0.5;
 draw();
}

function disminuir()
{
  rotation=rotation-0.5;
  draw();
}

你可以在以下网址找到所有这些:

https://gist.github.com/anonymous/0371ad6ec1bbfabed80a

1 个答案:

答案 0 :(得分:0)

您必须使用clearRect

   context.save(); // save state
   context.setTransform(1, 0, 0, 1, 0, 0); // set to indentity
   context.clearRect(0, 0, canvas.width, canvas.height); // clear
   context.restore();  // restore state

http://jsfiddle.net/nuk4mnrw/