2013-06-04 199 views
0

我有这14个矩形的行;我只想显示5行数,让用户滚动到可以看到所有14行。如何绘制可滚动的东西?

enter image description here

for(i=0;i<(canvas.height-200)/RECT_H;i++){ 
    drawRecord(Math.floor((Math.random()*10000)+1),x,y); 
    y+=RECT_H; 
} 
function drawRecord(number,x,y){ 
    context.strokeRect(x, y, RECT_W, RECT_H); 
    context.strokeRect(x+RECT_W, y, RECT_W*2, RECT_H); 
    context.font = 15 + 'px Lucida Sans'; 
    context.fillText(number, x-10*number.toString().length,y+RECT_H/1.5); 
} 

我如何能实现呢?

回答

0

如何在画布元素内制作可滚动行的示例。

这是一个javascript示例,我使用了mootools框架,但可以很容易地更改为使用其他框架。在画布上使用鼠标滚轮滚动行。创建旋钮也很好,因为这会创建表格大小和画布大小之间的比率,并使用该比例绘制矩形,矩形的位置取决于表格的当前顶部值。

<canvas id="canvas" width="400" height="300"></canvas> 
<script> 
    var canvas = $('canvas'); 
    var context = canvas.getContext('2d'); 

    var RECT_H = 30; 
    var RECT_W = 100; 
    var TEXT_X = 50; 

    var count = 14;  // number of rows 
    var y = 0;   // current top value of the table 
    var numbers = []; // numbers to display 

    for (var i=0; i<count; i++) {  // create array of numbers 
     numbers[i] = Math.floor((Math.random()*10000)+1); 
    } 
    drawRecords(); // draw initial records 

    function drawRecords() { 
     for (var i=0; i<count; i++) { 
      var top = (i*RECT_H) + y;  // top value of the current row 
      context.strokeRect(TEXT_X, top, RECT_W, RECT_H); 
      context.strokeRect(TEXT_X+RECT_W, top, RECT_W*2, RECT_H); 
      context.font = '15px Lucida Sans'; 
      context.fillText(numbers[i], TEXT_X-10*numbers[i].toString().length, top+RECT_H/1.5); 
     } 
    } 

    $('canvas').addEvent('mousewheel', function(e) { 
     // calculate the current top value of the table based on the mousewheel event 
     y = onMouseWheel(e, y, canvas.height - (count*RECT_H), 0, 10); 
     context.clearRect(0, 0, canvas.width, canvas.height); // clear canvas 
     drawRecords(); // redraw canvas 
    }); 

    function onMouseWheel(e, current_top, max, min, step) { 
     if (max < min) { 
      e.preventDefault();  // prevents window to move 
      if (e.wheel > 0) return current_top + step < min ? current_top + step : min; 
      else if (e.wheel < 0) return current_top - step > max ? current_top - step : max; 
     } 
     return 0; 
    } 
</script> 
相关问题