0

我有这 14 行是矩形的;我只想显示 5 行,让用户滚动到可以看到所有 14 行。

在此处输入图像描述

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);
}

我该如何实施?

4

1 回答 1

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>
于 2013-06-04T21:15:49.177 回答