【问题标题】:Drawing square inside another square using angularjs and canvas tags使用angularjs和canvas标签在另一个正方形内绘制正方形
【发布时间】:2014-08-29 05:10:29
【问题描述】:

我有这个plunker,我正在尝试使用 angularjs 制作多个正方形。我在html页面中使用<canvas>标签。

我有一个函数calc(),在该函数中,我将每次迭代的高度和宽度值减少一半。目标是绘制一系列正方形,其中每个下一个正方形都在前一个正方形内绘制。每个子方块的高度和宽度必须是其父方块的一半,并且水平和垂直居中。

我不知道如何在代码中继续绘制循环中的剩余方块

<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>

【问题讨论】:

    标签: javascript html css angularjs


    【解决方案1】:

    像这样? (可能更有效,但我试图保持你原来的结构)

    <script>
        var app = angular.module('keycount', []);
        app.controller('keycountcontroller', function($scope, $log, $http) {
          $scope.width = 500;
          $scope.height = 500;
    
          $scope.calc = function() {
            var x = $scope.width;
            var y = $scope.height;
            var parent = $('#myCanvas');
            while (x > 1) {
              x = x / 2;
              y = y / 2;
              var child = $(parent).clone(false)[0];
              $(child).css('width', x);
              $(child).css('height', y);
              $(child).css('position', 'relative');
              $(child).css('top', y/2);
              $(child).css('left', x/2);
              $(parent).append(child);
              parent = child;
              //alert(x);
            }
          }
    
          $scope.calc();
        });
      </script>
    </head>
    
    <body ng-controller="keycountcontroller">
      <div id="myCanvas" style="border:1px solid #000000; width:{{width}}px; height:{{height}}px;"></div>
    </body>
    

    首先我认为使用指令会使它变得更好,肯定更令人印象深刻,但不会更有效。因此,这里有一个更紧凑的版本:

    <script>
        var app = angular.module('keycount', []);
        app.controller('keycountcontroller', function($scope, $timeout) {
          $scope.width = 300;
          $scope.height = 300;
    
          $scope.calc = function() {
            var x = $scope.width;
            var y = $scope.height;
            var parent = $('#myCanvas');
            while (x > 1) {
              var child = $(parent).clone(false).css({ width: x = x / 2, height: y = y / 2, position: 'relative', top: x/2, left: y/2 });
              $(parent).append(child);
              parent = child;
            }
          }
        });
      </script>
    </head>
    
    <body ng-controller="keycountcontroller" ng-init="calc()">
      <div id="myCanvas" style="border:1px solid #000000; width:{{width}}px; height:{{height}}px;"></div>
    </body>
    

    【讨论】:

    • 我想知道你描述的更有效的方法:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多