如何不断更新这些坐标?

时间:2011-06-25 16:45:26

标签: javascript html

我想水平移动矩形,但是,它会多次进入updateStageObjects()函数,但不会更新myRectangle.x的值。如何解决这个问题?

 <script type="text/javascript">
            var interval = 10;
            var x=0;
            var y=0;
            var myRectangle;
            var context ;
            var canvas;
        function Rectangle(x, y, width, height, borderWidth) {
                this.x=x;
                this.y=y;
                this.width = width;
                this.height = height;
                this.borderWidth = borderWidth;
            }
        function DrawRects(){   
                myRectangle = new Rectangle (250,70,100,50, 5);      context.rect(myRectangle.x,myRectangle.y,myRectangle.width,myRectangle.height);        
                context.fillStyle="#8ED6FF";
                context.fill();
                context.lineWidth=myRectangle.borderWidth;
                context.strokeStyle="black"; 
                context.stroke();
            }

            function updateStageObjects() {
                var amplitude = 150;
                var centerX = 240;  
                myRectangle.x += 100;
    alert(myRectangle.x+"   "+myRectangle.y);                   
            }    
            function clearCanvas() {                
                context.clearRect(0,0,canvas.width, canvas.height); 
            }

            function DrawRect(){

                setTimeout(CheckCanvas,10);
                clearCanvas();
                updateStageObjects();
                DrawRects();
            }   
        function CheckCanvas(){
                return !!(document.createElement('canvas').getContext);

            }   

        function CheckSound(){
            return !!(document.createElement('sound').canPlayType)
            }

        function CheckVideo(){
            return !!(document.createElement('video').canPlayType)
            }

        function Checkstorage(){    
            return !!(window.localStorage)
            }


        function CheckVideo(){
            return !!(document.createElement('video').canPlayType)  
            }


        function DrawCanvas(){
            if (CheckCanvas()){
                canvas = document.getElementById('Canvas');
                DrawRects();
                setInterval(DrawRect, 10);      
            }
    }
</script>

HTML

   <canvas id="Canvas" width="800px" height="800px" onclick="DrawCanvas()"> Nor   supported</canvas>

2 个答案:

答案 0 :(得分:2)

正如Chris已经指出你的DrawRects()总是绘制相同的co-ords,尝试添加更多的变量,如

var dx = 250;
var dy = 70;

然后将new Rectangle更改为

myRectangle = new Rectangle (dx,dy,100,50, 5);

接下来将您的myRectangle.x += 100行更改为

dx += 100;

希望这有帮助。

答案 1 :(得分:1)

每次拨打updateStageObjects()时,都会立即致电DrawRects(),这会在(250,70,100,50, 5)处创建一个新的矩形。所以你永远不会注意到它的增量为100。

如果您希望其中一个人记住在另一个函数中所做的更改,您需要在这些函数之间来回传递一些数字。