我有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);
}
我该如何实现?
答案 0 :(得分:0)
如何在canvas元素中创建可滚动行的示例。
这是一个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>