以下代码使用GPU.js(一种WebGL的包装器),通过简单地编写JS函数,就可以轻松地使用WebGL运行矩阵运算,在画布上渲染图像,但我想调整其大小。我已经read about nearest neighbor interpolation,但是我对如何实现它感到困惑。我已经设置了调整大小的内核,剩下要做的就是内插逻辑。
注意:
根据内核所计算矩阵的维数,内核函数中的当前索引分别为this.thread.x
,this.thread.y
和this.thread.z
。
您会注意到画布的尺寸很奇怪。这是与WebGL纹理处理相关的GPU.js的“功能”(我认为他们计划稍后进行修复)。
编辑:取得了进步,但还不够完善:http://jsfiddle.net/0dusaytk/59/
const canvas1 = document.createElement("canvas");
const context1 = canvas1.getContext("webgl2");
document.body.appendChild(canvas1);
const canvas2 = document.createElement("canvas");
const context2 = canvas2.getContext("2d");
const gpu = new GPU({
canvas: canvas1,
webGl: context1
});
const image = new Image();
image.crossOrigin = "Anonymous";
image.src = "https://i.imgur.com/sl2J6jm.jpg";
image.onload = function() {
const length = 4 * image.height * image.width;
const gpuTexturize = gpu
.createKernel(function(sprite) {
return sprite[this.thread.x];
})
.setOutput([length])
.setOutputToTexture(true);
const gpuResize = gpu
.createKernel(function(sprite, w, h) {
return sprite[this.thread.x];
})
.setOutput([length])
.setOutputToTexture(true);
const gpuRender = gpu
.createKernel(function(sprite, w, h) {
var index = this.thread.x * 4 + (h - this.thread.y) * w * 4;
var r = sprite[index];
var g = sprite[index + 1];
var b = sprite[index + 2];
this.color(r / 255, g / 255, b / 255);
})
.setOutput([image.width, image.height])
.setGraphical(true);
canvas2.width = image.width;
canvas2.height = image.height;
context2.drawImage(image, 0, 0);
const imgData = context2.getImageData(
0,
0,
canvas2.width,
canvas2.height
);
const texture = gpuTexturize(imgData.data);
const resized = gpuResize(texture, 100, 100);
gpuRender(resized, image.width, image.height);
};
body {
background-color: #3a4659;
}
canvas {
background-color: #bcc8db;
}
<script src="https://rawgit.com/gpujs/gpu.js/develop/bin/gpu.js"></script>