使用Cordova Camera Plugin绘制图像绘制画布

时间:2017-04-19 10:41:19

标签: javascript cordova canvas html5-canvas pixi.js

我从设备获取图像并使用Pixi JS绘制带过滤器的画布。它可以很好地利用计算机来获取图像。但是当我在IOS上时,它会抛出诸如交叉原点问题之类的错误,或者我试图使用未知格式。

这是我用来绘制图片的代码(适用于网络/桌面,但不适用于Cordova内置的ios应用)

_renderImage() {
    let wWidth;
    if (window.outerWidth > 414) {
      wWidth = 414;
    } else {
      wWidth = window.outerWidth;
    }

    const img = new Image();
    img.src = this.state.avatarSource;

    let lower;
    if (img.width > img.height) {
      lower = img.height;
    } else {
      lower = img.width;
    }

    const canvas = this.refs.canvasimg;
    if (canvas.hasChildNodes()) {
      canvas.removeChild(canvas.childNodes[0]);
    }

    const renderer = PIXI.autoDetectRenderer(wWidth, wWidth * 1.25, {transparent: true});
    const stage = new PIXI.Container();

    canvas.appendChild(renderer.view);

    // create a PIXI sprite from an image path
    const canvasImg = PIXI.Sprite.fromImage(this.state.avatarSource);
    canvasImg.anchor.x = 0;
    canvasImg.anchor.y = 0;
    canvasImg.width = wWidth;
    canvasImg.height = wWidth * 1.25;

    const filter = this._getImageFilter();

    stage.filters = [filter];
    stage.addChild(canvasImg);

    render();

    function render(){
      requestAnimationFrame(render);
      renderer.render(stage);
    }
  }

这是我用来使用cordova相机插件选择图像的代码:

_getPhoto(isPhotosLib) {
    const captureSuccess = (imageData) => {
      this.m.setState({
        // avatarSource: `data:image/jpeg;base64,${imageData}`
        avatarSource: imageData
      })
    };

    const captureError = (error) => {
      navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
    };

    let options = {
      quality: 100,
      targetWidth: 640,
      targetHeight: 640,
      saveToPhotoAlbum: false,
      destinationType: Camera.DestinationType.FILE_URI,
      popoverOptions: new CameraPopoverOptions(640, 640, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
    }

    isPhotosLib ? options.sourceType = Camera.PictureSourceType.PHOTOLIBRARY : null;

    navigator.camera.getPicture(captureSuccess, captureError, options);
  }

我得到的错误是:

Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin.

在XCode上:

[Generic] Creating an image format with an unknown type is an error

当我更改为NATIVE_URI时,会记录此错误:

Failed to load resource: unsupported URL
assets-library://asset/asset.JPG?id=2DDAD0CF-2F82-40A0-B84B-398C996AC749&ext=JPG

那么它可能是什么原因导致它无法在ios上运行?

2 个答案:

答案 0 :(得分:1)

查看有关Cordova Whitelist Plugin的帖子,它解决了我的大多数问题 我不知道您是否使用任何WKWebView插件,但cordova-wkwebview-engine插件也支持一些iOS特定的应用程序传输安全设置https://github.com/apache/cordova-plugin-wkwebview-engine

另一种解决方法是使用HTML输入标记来启动摄像头捕获:

<input type="file" capture="camera" accept="image/*" />

只听“改变”事件。

答案 1 :(得分:0)

选项部分,设置为DATA_URL:

destinationType: Camera.DestinationType.DATA_URL

这将获得base64格式的图像,要显示图像,添加

<img src="data:image/jpeg;base64,'+ imageData +'">

然后从这个 img 标签绘制画布