drawImage using toDataURL of an html5 canvas

大憨熊 提交于 2019-12-22 11:37:32

问题


What I am doing now is the following:

I am storing the state of a canvas using the toDataURL method and I am also trying to draw it on a canvas using the drawImage method.

Here is a snippet:

var lastState = states[10]; //states is an array that saves all the toDataURL of the canvas
var permCtx = canvas.getContext('2d');
var img = new Image();
img.onload=function(){
  permCtx.drawImage(img,0,0);
}
img.src=lastState;

I am getting the following error in the console:

414 (Request-URI Too Large)

Is there a way to draw an image on the canvas using only the toDataURL method?


回答1:


The mechanism you have used should work; what OS/browser/version are you seeing this error with?

Anyhow, despite the fact that this should work, it is not the most efficient if you are constructing data URLs and then restoring them in the same session. Instead, I would suggest creating a new not-in-DOM canvas to store your state, and use that to draw to the main canvas:

var states = [];
function saveState(ctx){
  var c = document.createElement('canvas');
  c.width  = ctx.canvas.width;
  c.height = ctx.canvas.height;
  c.getContext('2d').drawImage(ctx.canvas,0,0);
  states.push(c);
  return c;
}

function restoreState(ctx,idx){
  var off = idx==null ? states.pop() : states[idx];
  ctx.drawImage(off,0,0);
}


来源:https://stackoverflow.com/questions/5697617/drawimage-using-todataurl-of-an-html5-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!