使用
使用
如何使用Famo.us显示可以脱机使用的图像?
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);
这不会引发任何警告或错误,但会显示损坏的图像。有什么建议吗?即使我处于脱机状态,我也希望显示图像,但当我重新连接时,我会请求上传最新的图像。
Famo.us
中的ImageSurface
可以获取图像或base-64编码数据的url。
使用Blob
:
使用文件读取器readAsDataURL
var reader = new FileReader();
reader.onloadend = function () {
imageURL = reader.result;
}
reader.readAsDataURL(blob);
使用Canvas
:
有很多方法可以获得编码的base-64数据。Canvas
有另一种方法可以为您获取此字符串。
示例jsBin在这里
使用下面的示例片段,您可以了解如何使用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';