• 数字矩阵算法


     1 var canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d');
     2     var start = 1, end = 256, step = 30, direction = 'right';
     3     var len = end - start + 1, wLen = 1, hLen = 1, flag = 1;
     4     var sideLength = Math.ceil(Math.sqrt(len)); // 总数求边长
     5     var currentX = step*(sideLength-1)/2, currentY = step*(sideLength+2)/2;
     6 
     7     ctx.moveTo(currentX, currentY);
     8     ctx.font = "14px sans-serif";
     9     // ctx.fillRect(0,0, canvas.width, canvas.height)
    10     ctx.fillStyle = "#000";
    11     console.log(sideLength);
    12     while (len--) {
    13         currentX += getXY(direction).x;
    14         currentY += getXY(direction).y;
    15         
    16         ctx.fillText(start++, currentX, currentY);
    17 
    18         ctx.moveTo(currentX, currentY);
    19         
    20         if (direction == 'up' && flag > hLen) {
    21             hLen++;
    22             direction = 'right';
    23             flag = 1;
    24         } else if (direction == 'right' && flag > wLen) {
    25             wLen++;
    26             direction = 'down';
    27             flag = 1;
    28         } else if (direction == 'down' && flag > hLen) {
    29             hLen++;
    30             direction = 'left';
    31             flag = 1;
    32         } else if (direction == 'left' && flag > wLen) {
    33             wLen++;
    34             direction = 'up';
    35             flag = 1;
    36         }
    37 
    38         flag ++;
    39     }
    40 
    41     function getXY(dir) {
    42         var x = 0, y = 0;
    43         switch(dir) {
    44             case 'up':  
    45                 x = 0;
    46                 y -= step;
    47                 break;
    48             case 'right':  
    49                 x += step;
    50                 y = 0;
    51                 break;
    52             case 'down':  
    53                 x = 0;
    54                 y += step;
    55                 break;
    56             case 'left':  
    57                 x -= step;
    58                 y = 0;
    59                 break;
    60         }       
    61         return {x: x, y: y}
    62     }
    63   
  • 相关阅读:
    【项目】项目41
    【项目】项目40
    【项目】项目39
    【项目】项目38
    【项目】项目37
    15-155. Min Stack
    14-160. Intersection of Two Linked Lists
    13-169. Majority Element
    12-206. Reverse Linked List
    11-215. Kth Largest Element in an Array
  • 原文地址:https://www.cnblogs.com/zhoulingfeng/p/3399451.html
Copyright © 2020-2023  润新知