如何使用 Famo.us 离线显示图像

How to display an image offline using Famo.us

如何使用 Famo.us 显示可离线使用的图像?

A Famo.us 图像表面根据图像设置其内容 URL。但是,离线时,这个 URL 将不起作用。我尝试使用 HTTP 请求并将缓冲区转换为 Blob,然后为 Blob 创建 URI:

    // bytes = request.buffer of HTTP request
    // Make a Blob from the bytes
    var blob = new Blob([bytes], {type: 'image/jpg'});

    // Use createObjectURL to make a URL for the blob
    imageURL = URL.createObjectURL(blob);

    //Use Famo.us image surface API to display the image (http://famo.us/docs/api/latest/surfaces/ImageSurface)
    imageSurface.setContent(imageURL);

这不会引发任何警告或错误,但会显示损坏的图像。有什么建议么?我想即使在离线时也显示图片,但当我重新连接时,我会请求上传最新的图片。

ImageSurface in Famo.us可以对图片或base-64编码的数据取url。

使用Blob:

使用文件reader到readAsDataURL

 var reader  = new FileReader();

  reader.onloadend = function () {
    imageURL = reader.result;
  }

  reader.readAsDataURL(blob);

使用Canvas:

有很多方法可以获取编码的 base-64 数据。 Canvas 有另一种方法可以为您获取此字符串。

Example jsBin Here

使用下面的示例片段,您可以了解如何使用 Canvas.toDataURL

  var image = new Image();
  image.crossOrigin = 'anonymous'; // only needed for CORS, not needed for same domain.

  // create an empty canvas element
  var canvas = document.createElement("canvas");
  var canvasContext = canvas.getContext("2d");

  image.onload = function () {

    //Set canvas size is same as the picture
    canvas.width = image.width;
    canvas.height = image.height;

    // draw image into canvas element
    canvasContext.drawImage(image, 0, 0, image.width, image.height);

    // get canvas contents as a data URL (returns png format by default)
    imageURL  = canvas.toDataURL();
  };

  image.src = 'http://code.famo.us/assets/famous_logo.png';