Serialize canvas content to ArrayBuffer and deserialize again(将画布内容序列化为 ArrayBuffer 并再次反序列化)
问题描述
我有两个画布,我想把canvas1的内容传过来,序列化到一个ArrayBuffer中,然后加载到canvas2中.以后我会把canvas1的内容发送到服务器,处理后返回给canvas2,但是现在只想序列化和反序列化.
I have two canvases, and I want to pass the content of canvas1, serialize it to an ArrayBuffer, and then load it in canvas2. In the future I will send the canvas1 content to the server, process it, and return it to canvas2, but right now I just want to serialize and deserialize it.
我发现了这种以字节为单位获取画布信息的方法:
I found this way of getting the canvas info in bytes:
var img1 = context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array(img1.data.length);
for (var i = 0; i < img1.data.length; i++) {
binary[i] = img1.data[i];
}
还发现了这种将信息设置为Image
对象的方法:
And also found this way of set the information to a Image
object:
var blob = new Blob( [binary], { type: "image/png" } );
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL( blob );
var img = new Image();
img.src = imageUrl;
但不幸的是,它似乎不起作用.
But unfortunately it doesn't seem to work.
这样做的正确方法是什么?
Which would be the right way of doing this?
推荐答案
您从 getImageData()
获得的 ImageData 已经在使用 ArrayBuffer(由 Uint8ClampedArray
视图使用).抓住它并发送它:
The ImageData you get from getImageData()
is already using an ArrayBuffer (used by the Uint8ClampedArray
view). Just grab it and send it:
var imageData = context.getImageData(x, y, w, h);
var buffer = imageData.data.buffer; // ArrayBuffer
重新设置:
var imageData = context.createImageData(w, h);
imageData.data.set(incomingBuffer);
您可能想要考虑某种形式的字节编码(例如 f.ex base-64),因为任何高于 127 (ASCII) 的字节值都受系统上使用的字符编码的影响.或者确保旅途中的所有步骤都使用相同的(例如 UTF8).
You probably want to consider some form of byte encoding though (such as f.ex base-64) as any byte value above 127 (ASCII) is subject to character encoding used on a system. Or make sure all steps on the trip uses the same (f.ex. UTF8).
这篇关于将画布内容序列化为 ArrayBuffer 并再次反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将画布内容序列化为 ArrayBuffer 并再次反序列化
基础教程推荐
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01