zoukankan      html  css  js  c++  java
  • canvas中的rotate的使用方法

    今天在绘制一个足球滚动的时候,想使用rotate方法,之前看到这个方法的时候,并没有引起任何重视,无非就是和CSS3里的rotate一样的用么...

    遗憾的是,事实并非如此,由于代码在公司,我也就不去找那些图片资源了,直接用一个黑色方块代替

    代码如下:

    var oCan = document.getElementById("canvas");
    var ctx = oCan.getContext("2d");
    
    ctx.rotate(30 * Math.PI / 180);
    ctx.fillRect(50,50,100,100);

    显示结果如下:

    这...不能忍....于是乎打开了我心爱的w3school,发现一句有用的也没多说(心寒)

    下班后一路琢磨这个问题,终于想到,translate似乎可以改变坐标系的0,0点.

    恩,这应该有用,但是...试了几次,都失败了,百度搜了几篇文章,真的好废柴,都是错误的,继续搜,看到了一个老外写的(还得是老外)

    var x      = 10;
    var y      = 10;
    var width  = 100;
    var height = 100
    var cx     = x + 0.5 * width;   // x of shape center
    var cy     = y + 0.5 * height;  // y of shape center
    
    context.fillStyle = "#ff0000";
    context.fillRect(x, y, width, height);  //draw normal shape
    
    context.translate(cx, cy);              //translate to center of shape
    context.rotate( (Math.PI / 180) * 25);  //rotate 25 degrees.
    context.translate(-cx, -cy);            //translate center back to 0,0
    
    context.fillStyle = "#0000ff";
    context.fillRect(x, y, width, height);

    链接:http://tutorials.jenkov.com/html5-canvas/transformation.html#rotation

    这次,恍然大悟,正解!封装下吧,以后就用它了

    function fillRotateRect(context,x,y,width,height,degrees){
        var cx = x + 0.5 * width;
        var cy = y + 0.5 * height;
        context.translate(cx, cy);
        context.rotate( (Math.PI / 180) * degrees);
        context.translate(-cx, -cy);
        context.fillRect(x,y,width,height);
    }

    但这个方法只能绘制正方形,遇到图片,或者圆形,就又得改动,有时间了再思考怎么封装一个比较妥善的吧.先到这里了

  • 相关阅读:
    Java -- Map
    Bootstrap -- 标签属性
    SQLServer -- 竟然默认不区分大小写
    ThinkPHP -- 问题
    ThinkPHP
    MVC-内容详情页显示内容
    未能加载文件或程序集“Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed”或它的某一个依赖项。
    Random.Next获取随即数
    Razor语法小记
    VisualStudio自定义代码段_方法二
  • 原文地址:https://www.cnblogs.com/liqingchang/p/4433737.html
Copyright © 2011-2022 走看看