如何让html画布无限期地"滚动"?

mag*_*mag 6 html javascript canvas

我有一个canvas元素,在加载时会自动填充客户端的整个浏览器窗口.在它上面你可以用鼠标绘制,就像任何"制作绘图板"的结果一样.然而,我想要做的是,如果你将鼠标移动到画布的任何极端(或者可能选择某个"移动"工具,你可以沿你想要的任何方向拖动画布),它滚动.特别是,我希望理论上可以永久滚动,所以我不能真正预生成,我必须动态生成"更多画布".有没有人知道如何做到这一点?

如果它有帮助,这就是客户端javascript :( html只是一个canvas-tag)

$(document).ready(function() {
    init();
});

function init() {
    var canvas = document.getElementById('canvas')
      , ctx = canvas.getContext('2d')
      , width = window.innerWidth
      , height = window.innerHeight;

    // Sets the canvas size to be the same as the browser size
    canvas.width = width;
    canvas.height = height;

    // Binds mouse and touch events to functions
    $(canvas).bind({
        'mousedown':  startDraw,
        'mousemove':  draw,
        'mouseup':    stopDraw,
    });
};

// Triggered on mousedown, sets draw to true and updates X, Y values.
function startDraw(e) {
    this.draw = true;
    this.X = e.pageX;
    this.Y = e.pageY;
};

// Triggered on mousemove, strokes a line between this.X/Y and e.pageX/Y
function draw(e) {
    if(this.draw) {
        with(ctx) {
            beginPath();
            lineWidth = 4;
            lineCap = 'round';
            moveTo(this.X, this.Y);
            lineTo(e.pageX, e.pageY);
            stroke();
        }
        this.X = e.pageX;
        this.Y = e.pageY;
    }
};

// Triggered on mouseup, sets draw to false
function stopDraw() {
    this.draw = false;
};
Run Code Online (Sandbox Code Playgroud)

Tor*_*ker 2

canvas 元素使用计算机的真实内存,因此不存在永远滚动的无限画布。但是,您可以使用虚拟画布来模拟此行为。只需将draw()捕获的xy坐标记录到一个数组中,并在鼠标触摸边框时计算虚拟画布的新中心。然后过滤出适合中心+-屏幕尺寸的xy坐标并绘制它们。

然而,记录 xy 坐标的数组不能无限增长,并且过滤器代码将随着数组的大小而变慢。10000积分够吗?

更优化的代码会将鼠标坐标转换为样条曲线,并仅保存重绘鼠标(平滑)路径所需的点。