toDataURL() of webgl canvas returning transparent image in iOS only

房东的猫 提交于 2021-02-18 22:43:24

问题


I have a canvas with webGL-drawings, created by Blend4Web framework.

I tried to save image using toDataURL():

image= $('canvas')[0].toDataURL();

All platforms works perfect, except iOS (iphone & ipad)

I know about webGL aspects: Canvas toDataURL() returns blank image only in Firefox, preserveDrawingBuffer is enabled.

Also, I know about limitations in iOS: iOS HTML5 Canvas toDataURL, but canvas is small, even 100×500px images are blank (it is 0,05MP, limit is 3MP).

I use toDataURL() to send graphic information on server.


回答1:


The following is a polyfill of toDataURL. In order to get toBlob to work on iOS, you need an additional polyfill, I recommend the following polyfill: https://github.com/blueimp/JavaScript-Canvas-to-Blob. Basically just download the canvas-to-blob.min.js. I would have recommended a direct toDataURL polyfill by someone else, but I could not find one.

if (typeof HTMLCanvasElement.prototype.toDataURL !== "function") {
  HTMLCanvasElement.prototype.toDataURL = function() {
    this.toBlob(function (blob) {
      var fileReader = new FileReaderSync();
      return fileReader.readAsDataURL(blob);
    });
  };
}



回答2:


1) Try get image after some tiomeout

window.setTimeout(function(){var result = $('canvas')[0].toDataURL();
},100);

2)Before get image url, you can check canvas for transparent pixels

var canvas = $('canvas')[0];
var ctx = canvas .getContext("2d")
var data = ctx.getImageData(0,0,canvas .width,canvas .height);
console.dir(data);//empty pixel it is each [0,0,0,0] array (rgba(0,0,0,0))

3) Try to write your canvas on other canvas

var canvas = $('canvas')[0];
var tmpCanvas = document.createElement("canvas");
tmpCanvas.width = canvas.width;
tmpCanvas.height = canvas.height;
tmpCanvas.getContext("2d").drawImage(canvas,0,0,tmpCanvas.width,tmpCanvas.height,0,0,tmpCanvas.width,tmpCanvas.height);
var result = tmpCanvas.toDataURL(); 

4) Try to send blobs to server instead of base64, it is more memory friendly: https://stackoverflow.com/a/34924715/5138198

5) or maybe better just read this post: https://stackoverflow.com/a/45223017/5138198



来源:https://stackoverflow.com/questions/47009400/todataurl-of-webgl-canvas-returning-transparent-image-in-ios-only

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