我在一维数组中有来自二维图像的数据,情节很完美,但我想要反转y轴。我看到了ctx.transform
的提示,但它似乎不适用于此示例:
https://jsfiddle.net/92j9r2j4/2/
Z阵列就是例如,Z [n * n-1]用于标记角落。
答案 0 :(得分:2)
ctx.putImageData
不受转化影响。图像数据函数getImageData和putImageData不受当前转换的影响。它们是记忆blit(移动)函数而不是图形函数。
您有几种选择。
在这种情况下,您可以正常创建数据,但在将内容复制到画布后,您可以使用变换ctx.setTransform(1,0,0,-1,0,n - 1)
在自身上绘制画布。如果您有透明像素,则需要使用复合模式"copy"
来替换像素而不是混合它们。
var i,j;
const n = 200;
const size = n ** 2; // ** is to power of
//const canvas = document.querySelector('canvas'); // not needed canvas is
// already defined with
// id="canvas"
const ctx = canvas.getContext("2d");
const imgData = ctx.createImageData(n, n);
const Z = [];
for (j = 0; j < size; j ++) { Z[j] = j * 256 / size }
Z[n * n - 1] = 0;
i = 0;
for (j = 0; j < size; j++) {
imgData.data[i++] = Z[j];
imgData.data[i++] = Z[j];
imgData.data[i++] = Z[j];
imgData.data[i++] = 255;
}
ctx.putImageData(imgData, 0, 0);
// flip the canvas
ctx.transform(1, 0, 0, -1, 0, canvas.height)
ctx.globalCompositeOperation = "copy"; // if you have transparent pixels
ctx.drawImage(ctx.canvas,0,0);
ctx.globalCompositeOperation = "source-over"; // reset to default
&#13;
<canvas id="canvas" width=200 height=200></canvas>
&#13;
在这种情况下,通过计算每个像素的翻转索引,在将数据从数组复制到图像数据数组时翻转数据。
var i,j;
const n = 200;
const size = n ** 2; // ** is to power of
const ctx = canvas.getContext("2d");
const imgData = ctx.createImageData(n, n);
const Z = [];
for (j = 0; j < size; j++) { Z[j] = j * 256 / size }
Z[size - 1] = 0;
var i = 0;
for (j = 0; j < size; j++) {
// get the index mirrored pixel
i = (((n - 1) - ((j / n) | 0)) * n + (j % n)) * 4;
imgData.data[i++] = Z[j];
imgData.data[i++] = Z[j];
imgData.data[i++] = Z[j];
imgData.data[i++] = 255;
}
ctx.putImageData(imgData, 0, 0);
&#13;
<canvas id="canvas" width=200 height=200></canvas>
&#13;
在此示例中,您将创建数据翻转。
不是这个例子,数据在x和y中翻转。注册商标保持不变。
var i,j;
const n = 200;
const size = n ** 2; // ** is to power of
const ctx = canvas.getContext("2d");
const imgData = ctx.createImageData(n, n);
const Z = new Uint8Array(n*n); // use an 8 bit array as a standard array will
// will be marked as sparse (slow) if you add
// out of order
for (j = 0; j < size ; j ++) {
// reverse the order of values
Z[size - 1 - j] = j * 256 / size;
}
Z[n - 1] = 0; // add black pixel at top right
i = 0;
for (j = 0; j < size; j ++) {
imgData.data[i++] = Z[j];
imgData.data[i++] = Z[j];
imgData.data[i++] = Z[j];
imgData.data[i++] = 255;
}
ctx.putImageData(imgData, 0, 0);
&#13;
<canvas id="canvas" width=200 height=200></canvas>
&#13;