我有一个带有FabricJS画布的页面。当用户按下某个按钮时,会向Web服务发送请求。响应包含PNG图像的数据,我想将其插入到画布中。
在下面的代码段中,图片数据包含在$ xhr.responseText中。
function downloadButtonPressed() {
var username = $("input#username").val();
var password = $("input#password").val();
$.ajax({
type: "GET",
url: "http://myserver/myapp/map",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password),
},
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function (data, status, xhr) {
alert("success");
}
}).fail(function ($xhr) {
console.log("response: " + $xhr);
// Here, $xhr.responseText contains the data of the PNG image
});
}
我想将$xhr.responseText
的PNG图像添加到FabricJS画布。
我该怎么做?
有一个方法fabric.Image.fromURL
,但我需要一些东西,它将字符串(或字节流)转换为FabricJS图像。
答案 0 :(得分:2)
如果您的回复文本是包含图像数据的二进制字符串,则可以构建dataurl并从datayurl加载标准图像。
function downloadButtonPressed() {
var username = $("input#username").val();
var password = $("input#password").val();
$.ajax({
type: "GET",
url: "http://myserver/myapp/map",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password),
},
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function (data, status, xhr) {
alert("success");
}
}).fail(function ($xhr) {
var myDataURL = "data:image/png;base64," + btoa($xhr.responseText);
var img = document.createElement("IMG");
img.onload = function(){
var fImg = new fabric.Image(img, {options});
}
img.src = myDataURL
});
}
如果您的响应是utf8字符串,因此会产生非法字符的错误,如MDN所述,请尝试使用此替代解决方案将其转换为基数64:
https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa
function utf8_to_b64(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
btoa(unescape(encodeURIComponent($xhr.responseText)));
答案 1 :(得分:0)
import { BLE } from '@ionic-native/ble/ngx';
devices:any[] = [];
id;
constructor(
public plt: Platform,
private route: ActivatedRoute,
private ble: BLE,
private ngZone: NgZone,
private cd: ChangeDetectorRef,
) { }
connect(count:number){
this.ble.connect(this.devices[count].id).subscribe
(peripheralData => {
console.log(peripheralData);
},
peripheralData => {
console.log('disconnected');
});;
this.id = this.devices[count].id;
}
write(){
if (this.ble.isConnected){
console.log("WE ARE CURRENTLY CONNECTED");
var string = "HELLO"
var array = new Uint8Array(string.length);
for (var x = 0, l = string.length; x < l; x++)
{array[x] = string.charCodeAt(x);}
this.ble.writeWithoutResponse(this.id, "6E400001-B5A3-F393-E0A9-
E50E24DCCA9E",
"6E400002-B5A3-F393-E0A9-E50E24DCCA9E", array);
}
else{
console.log("WE ARE NOT CONNECTED");
}
}