代码改变世界

HTML5 Canvas translate与rotate应用

2011-12-09 10:43 by LoujaDy, ... 阅读, ... 评论, 收藏, 编辑

Translate:坐标转化

默认Canvas的起启坐标0,0是在右上角,如果让中起启坐标放在中心点就可以这样做

context.translate(centerX,centerY);

 

Rotate:旋转的角度(确切的说是弧度)

弧度=角度*PI/180

角度=弧度*180/PI

 

下面的一个例子就是使用到了坐标转化和旋转

按左右键可以让方块转动 

 //获取Canvas对象

         var canvas=document.getElementById("stage");
        var context=canvas.getContext("2d");    
        
        //矩形大小
        var width=100;
        var height=100;
        
        
        //旋转频率
        var angelSpeed=5;
        
        //中心点位值
        var centerX=canvas.width/2;
        var centerY=canvas.height/2;
        
        //绘制钜形
        //将坐标中心作为起启点
        context.translate(canvas.width/ 2, canvas.height/ 2);
        DrawRect(0);
            
            
        //添加键盘处理事件        
         window.addEventListener("keydown", onKeyDown, false); 

          function onKeyDown(evt)
            {
                if(evt.keyCode=="39")
                {
                    
                        DrawRect(angelSpeed);                
                }
                else if(evt.keyCode=='37')
                {
                    
                      DrawRect(-angelSpeed);
                }
                
            }
            
            function DrawRect(speed)
            {
                
                context.clearRect(-width/2-width,-height/2-height, canvas.width, canvas.height);                        
                context.beginPath();         
                context.strokeStyle = '#ff0000'
                context.fillStyle='#ff0000';                
        
                //旋转
                context.rotate(speed*Math.PI/180);
                context.fillRect(-width/2,-height/2,width,height);
                context.fill();
                context.stroke();                
                context.closePath();    
                
                    
            }            

作者:Louja
出处:http://loujady.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此声明,且在文章页面给出原文连接,否则保留追究法律责任的权利。