Konvajs - Layer.toImage() return null 而不是图像数据

Konvajs - Layer.toImage() return null instead of the image data

我目前正在处理舞台的图层,该图层在按钮事件上导出为 png 文件,它正在工作,但直到我将徽标作为图像 class 添加到该图层。

不添加图像元素:

layer.toImage({
   callback: function(img) { //img = "base_64 image data".
     console.log(img.src);
   }
});

使用图像元素:

layer.toImage({
   callback: function(img) { //img = null
     console.log(img.src); // Error: src of null.
   }
});

在这里,应用程序崩溃了,我找不到问题所在。我尝试添加和删除图像,然后导出图像,效果很好。只有在图层中绘制图像元素时才会出现此问题。

知道为什么会这样吗?

更新

代码示例:

var myLayer= this.refs.layer;
myLayer.children.forEach(element => {
  if (element.attrs.elementType === "text"){
    if (element.isVisible()){
      element.visible(false);
      hiddenElements.push(element.id);
    }
  }
});

myLayer.toImage({
  callback: function(img) { //If image is drawn to the leyer img = null
    *Ajax function here*    //Else img has base64 info of the leyer
  },
  mimeType: "image/png"
});

然后我将所有 hiddenElements 设置回 true,舞台恢复到初始状态。

对于任何其他来到这里并想知道 'CORS'、Wikipedia introduces CORS 作为

的人

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos. Certain "cross-domain" requests, notably Ajax requests, are forbidden by default by the same-origin security policy.

这实际上意味着 canvas 无法将来自另一个(未启用 CORS)域的图像处理为 blob。如果它尝试,浏览器将强制出现 'Tainted canvas' 错误,您可以在浏览器控制台中观察到该错误。

Mike C to 的回复中对为什么会这样有一个精辟的解释,为了简洁起见,我将其复制到这里。

Imagine you have a bank statement open, which only you can view because of some kind of authentication header, but then a 3rd party creates a canvas element and inserts that image into the canvas. They could then convert that to a blob and send it back to home base if the canvas wasn't marked as "tainted"

事实证明,canvas 的好处也可能是陷阱。或者正如尤达所说 'Powerful you have become, the dark side I sense in you.'