jen*_*nsk 6 javascript jquery html5 canvas
我想创建一个实现虚拟HTML5 Canvas的jQuery插件,即一个物理上不比它在页面上出现的画布(或者不大得多).但是要在画布上显示的内容可能比画布大很多倍,并且会根据滚动条动态地重新绘制.
您会认为这是非常常见的功能,但到目前为止,我还无法使用jQuery插件或其他方式查找示例.这与例如SlickGrid为Div所做的非常类似,除了这是使用Canvas.我可以想到两个解决方案:
使用jQuery UI Slider将滚动条实现为完全独立的元素,并使用其事件来控制Canvas重绘.
做任何SlickGrid为Div做的事情.它似乎使Div略大于显示的内容,并且可以滚动事件来动态地向Div添加/删除元素.但我无法看到它如何修改滚动条以使其看起来好像在Div中有更多当前正在显示的内容.
你会推荐什么?示例代码将不胜感激.
我挖掘了SlickGrid代码并使用了方法2)(某种程度) - 这是我想到的:
/*
jensk@migselv.com
Simple virtual CANVAS controlled by a native scrollbar made with two DIVs
Uses jCanvas by Caleb Evans (http://calebevans.me/projects/jcanvas/index.php)
Thanks to Michael Leibman of SlickGrid fame for ideas.
Still need to clean it up (get rid of hardcoded values) and make it a nice, configurable
jQuery component.
Currently also redraws the entire canvas on each scroll event. Could be optimized to
do real browser scrolling and only redrawing the needed parts.
Another gotcha is that since it is the zero width DIVs that causes the scroll events,
mouse wheel, trackpad, touchscreen etc. scrolling over the Canvas will not work - only
the scrollbar is active. To solve this, one could make the Canvas larger inside a
smaller DIV too, catch scroll events from it and perform redrawing and setting the DIV's
scrollTop accordingly.
*/
var h = 10000; // virtual canvas height
var vp = 400; // viewport height
var viewport, fakescrolldiv, canvas;
function onScroll() {
var scrollTop = viewport.scrollTop();
console.log("onScroll scrollTop=" + scrollTop);
$("canvas").clearCanvas();
// Red box top
$("canvas").drawRect({
fillStyle: "#F00",
x: 150,
y: 20 - scrollTop,
width: 100,
height: 100,
fromCenter: false
});
// Green box middle
$("canvas").drawRect({
fillStyle: "#0F0",
x: 150,
y: 140 - scrollTop,
width: 100,
height: 100,
fromCenter: false
});
// Blue box bottom
$("canvas").drawRect({
fillStyle: "#00F",
x: 150,
y: 260 - scrollTop,
width: 100,
height: 100,
fromCenter: false
});
var i = 0;
for (i = 0; i <= 396; i++) {
$("canvas").drawLine({
strokeStyle: "#000",
strokeWidth: 1,
x1: 0,
y1: i,
x2: (scrollTop + i) % 50,
y2: i
});
if ((scrollTop + i) % 50 === 0) {
$("canvas").drawText({
fillStyle: "#729fcf",
text: (scrollTop + i).toString(),
align: "left",
baseline: "top",
font: "normal 12pt Verdana",
x: 60,
y: i
});
}
}
}
$(function() {
viewport = $("#viewport");
fakescrolldiv = $("#fakescrolldiv");
canvas = $("#gfx");
viewport.css("height", vp);
fakescrolldiv.css("height", h);
viewport.scroll(onScroll);
viewport.trigger("scroll");
});
Run Code Online (Sandbox Code Playgroud)
任何改进或简化的建议都非常感谢.