圆图不清除在90度

Circular drawing is not cleared at 90 degrees

本文关键字:90度 清除      更新时间:2023-09-26

我想在360度轨道上移动一个红色圆圈。

但在90度处,圆圈未清除。

这里是

代码: https://jsfiddle.net/Laqd0L36/3/

var i=0;
 function Rotate(ctx){
     i++;          
     if(i==360){                              
         i=0;
     }
     ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
 //Radius of orbit * i(degree) * convert to radian
     x = 140*Math.cos(i*Math.PI/180);
     y = 140*Math.sin(i*Math.PI/180);
     Circle(ctx,x,y);
     }
 function Circle(ctx,x,y){
     ctx.fillStyle = 'rgb(255,35,55)';
     ctx.beginPath();
     ctx.arc(x,y,12,0,Math.PI*2,true);
     ctx.fill();
     ctx.closePath();
     }
 function CtxInterval(){
     var can = document.getElementById("can");
     var ctx = can.getContext("2d");
     ctx.translate(150,150);
     setInterval(function(){Rotate(ctx);},10);
 }
 CtxInterval();

当您通过150, 150翻译上下文时,您需要在-150, -150开始您的clearRect矩形。(这是你更新的小提琴)

@Teemu的评论是更优雅的解决方案,即

去掉ctx.translate(150, 150), arc()中的x和y加150

 var i=0;
 function Rotate(ctx){
     i++;          
     if(i==360){                              
         i=0;
     }
     console.log("width: "+ctx.canvas.width+ "height: "+ctx.canvas.height);
     ctx.clearRect(-150,-150,ctx.canvas.width,ctx.canvas.height);
 //Radius of orbit * i(degree) * convert to radian
     x = 140*Math.cos(i*Math.PI/180);
     y = 140*Math.sin(i*Math.PI/180);
     Circle(ctx,x,y);
     }
 function Circle(ctx,x,y){
     ctx.fillStyle = 'rgb(255,35,55)';
     ctx.beginPath();
     ctx.arc(x,y,12,0,Math.PI*2,true);
     ctx.fill();
     ctx.closePath();
     }
 function CtxInterval(){
     var can = document.getElementById("can");
     var ctx = can.getContext("2d");
     ctx.translate(150,150);
     setInterval(function(){Rotate(ctx);},10);
 }
 CtxInterval();