【问题标题】:How to draw something scrollable?如何绘制可滚动的东西?
【发布时间】:2013-06-05 05:15:49
【问题描述】:

我有这 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);
}

我该如何实现?

【问题讨论】:

    标签: javascript html canvas drawing


    【解决方案1】:

    如何在画布元素中创建可滚动行的示例。

    这是一个 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>
    

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多