javascript 使用数据 URL 的画布 drawImage

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3379893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:01:29  来源:igfitidea点击:

Canvas drawImage using data URL

javascripthtmlcanvas

提问by Firstmate

I'll start with the script:

我将从脚本开始:


  function saveInstance() {
   _savedInstance = document.getElementById('canvasID').toDataURL();
  }
  function restoreInstance() {
   ctx.drawImage(_savedInstance,0,0);
  }

The purpose is to save an instance of the canvas and re-apply it later [Similar to how ctx.save() saves the style and transformations].

目的是保存画布的一个实例,稍后重新应用[类似于ctx.save()保存样式和变换的方式]。

However, I got the error that says incompatible types (Uncaught Error: TYPE_MISMATCH_ERR: DOM Exception 17). Is there any canvas method that will allow me to use the data URL string to re-draw the instance?

但是,我收到了不兼容类型的错误(未捕获错误:TYPE_MISMATCH_ERR:DOM Exception 17)。是否有任何画布方法可以让我使用数据 URL 字符串重新绘制实例?

**If there's a better way to implement this save/restore idea I have, that'd also be much appreciated.

**如果有更好的方法来实现我的这个保存/恢复想法,那也将不胜感激。

-Firstmate

-大副

回答by pixl coder

Yes, you can create an image element with its source as _savedInstanceand then draw it to the canvas.

是的,您可以使用其源创建一个图像元素,_savedInstance然后将其绘制到画布上。

var img = new Image();
img.src = _savedInstance;
ctx.drawImage(img,0,0);