【问题标题】:Use Javascript to store and restore a canvas使用 Javascript 存储和恢复画布
【发布时间】:2013-03-11 12:11:25
【问题描述】:

我想使用 JavaScript 来存储(以某种方式记住)画布元素的当前状态(显示的图像),然后稍后恢复它。

var cvSave;  //Global variable to save ImageData

function function1(){
//some stuff wich involes putting an image into a canvas
cvSave = context.getImageData(0,0,viewport.width, viewport.height);
// All the variables are existing and I use the context to put Stuff into the canvas which works fine
}

function isCalledLater(){
var canvas = document.getElementById('cv');
var ctx = canvas.getContext('2d');          //Get canvas and context
ctx.putImageData(cvSave,0,0);               //So this should restore the canvas to what I save earlier, right?
}

但是当第二个函数被调用时,它只会将画布变成白色,并且不会将它恢复到我认为我在 cvSave 中保存的内容。

我希望这是客户端,我想将其恢复到我多次保存的状态。

在恢复画布后也很重要(我一开始忘记了),我想使用 Processingjs 在恢复图像上绘制,然后我希望能够再次执行此操作。

感谢您的帮助。

【问题讨论】:

  • 您是否忘记定义一个在 function1 命名上下文中使用的全局变量?

标签: javascript html5-canvas


【解决方案1】:

嘿试试这个..

var cvSave;  //Global variable to save ImageData

function function1(){
//some stuff wich involes putting an image into a canvas
context.save();
// All the variables are existing and I use the context to put Stuff into the canvas which works fine
}

function isCalledLater(){
var canvas = document.getElementById('cv');
var ctx = canvas.getContext('2d');          //Get canvas and context
ctx.restore(); //So this should restore the canvas to what I save earlier, right?
ctx.save();  // this will save once again           
}

【讨论】:

  • 我试过这个。我得到了一些奇怪的错误。由于某种原因,它没有正确恢复画布。
  • 尝试不使用函数 isCalledLater() 中的 ctx.save() 。因为restore方法的工作是返回之前保存的路径状态和属性所以应该可以工作...
【解决方案2】:

我尝试了这里建议的大部分内容,但由于某种原因没有任何效果。

最后我做到了,这样我就有了一个状态,我总是想恢复并保存该状态,方法是将相应的图像绘制到另一个画布中,并在需要时从那里获取它。

【讨论】:

    【解决方案3】:

    您可以将 ajax 与 Web 服务器一起使用,该服务器本身存储数据或 cookie 以将数据存储为纯文本。看看这个:http://www.w3schools.com/js/js_cookies.asp

    【讨论】:

    • 考虑过,但我很乐意将其保留在客户端。
    • 查看链接,它是客户端。您只需为 cookie 命名,cookie 将保存在客户端浏览器中,稍后您可以读取该 cookie。如果您的数据不是纯文本,您可以将其编码/解码为 base64
    【解决方案4】:

    你可以使用

    cvSave = canvas.toDataURL("image/png");
    ctx.drawImage(cvSave,0,0);
    

    我认为你错过了一些东西。试试这个

    function function1(){
        var context = canvas.getContext('2d');
        cvSave = context.getImageData(0,0,viewport.width, viewport.height);
    }
    

    【讨论】:

    • 试过了,但它不起作用。有没有其他方法可以将内容设置为 Canvas,以便我可以以某种方式使用 toDataURL()?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 2011-08-13
    相关资源
    最近更新 更多