簡體   English   中英

HTML5 Canvas-在Canvas上繪制,保存上下文並稍后還原

[英]HTML5 Canvas - Draw on Canvas, Save Context and Restore it later

需求:

現在:在畫布上繪制,然后單擊保存(存儲畫布狀態/離線繪制-但不作為圖像)。
以后:打開畫布並顯示以前保存的圖形,然后繼續進行繪制。

對於繪制,我們通常使用如下代碼:

canvas = document.getElementById('can');
ctx = canvas.getContext("2d");
...
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
....

為了以后恢復Canvas狀態-導出到Image沒有幫助。
我想將“畫布”還原到其原始狀態,以便以后繼續編輯圖形。

我猜想,Canvas上下文必須離線導出和存儲-如何?

最好的選擇是使用一個代理,它既可以存儲繪制命令,也可以執行繪制。
由於瀏覽器對Proxy的支持非常糟糕(截至目前僅支持FF),因此您必須使用nosuchmethod或通過Context2D構建新的全新WatchedContext類來自行構建Proxy。
對於這個簡短的演示,我采用了最后一個解決方案(WatchedContext類):

function WatchedContext(hostedCtx) {
  this.commands= [];
  Context2dPrototype = CanvasRenderingContext2D.prototype;
  for (var p in Context2dPrototype ) {
    this[p] = function(methodName) {
        return function() {
            this.commands.push(methodName, arguments);
            return Context2dPrototype[methodName].apply(hostedCtx, arguments);
        }      
    }(p);
  }  
  this.replay=function() {
    for (var i=0; i<this.commands.length; i+=2) {
      var com = this.commands[i];
      var args = this.commands[i+1];
      Context2dPrototype[com].apply(hostedCtx, args);
    }
  }
}

顯然,您可能需要其他方法(開始/停止記錄,清除等)

只是一個小的使用示例:

var cv = document.getElementById('cv');
var ctx=cv.getContext('2d');
var watchedContext=new WatchedContext(ctx);

// do some drawings on the watched context
// --> they are performed also on the real context
watchedContext.beginPath();
watchedContext.moveTo(10, 10);
watchedContext.lineTo(100, 100);
watchedContext.stroke();

// clear context (not using the watched context to avoid recording)
ctx.clearRect(0,0,100,1000);

// replay what was recorded
watchedContext.replay();

您可以在這里看到:

http://jsbin.com/gehixavebe/2/edit?js,output

重放確實起作用,並且由於重放了存儲的命令,因此重新繪制了該行。

對於脫機存儲,您可以使用localStorage在本地存儲命令,也可以使用AJAX調用或類似方法將它們遠程存儲在服務器上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM