将2维像素阵列复制到Javascript画布 [英] Copy a 2-dimensional pixel array to a Javascript canvas

查看:143
本文介绍了将2维像素阵列复制到Javascript画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JavaScript canvas元素,是否可以将RGB值的二维数组复制到画布?

Using the Javascript canvas element, is it possible to copy a 2-dimensional array of RGB values to a canvas?

<html>
<body>
<canvas id="canvas" height="200" width="200"></canvas>
<script type = "text/javascript">

//copy the following array to the canvas:
var arr1 = [
[[255, 255, 255],[200, 200, 0],[200, 200, 200]],
[[200, 0, 0],[200, 200, 0],[200, 200, 0]],
[[200, 200, 0],[200, 0, 0],[200, 200, 0]]
]

<script>
</body>
</html>


推荐答案

可以使用 getImageData / putImageData 。只需计算正确的指数(它是一个大阵列中的RGBA值): http://jsfiddle.net/zjypd/

You can use getImageData/putImageData. Just calculate the right index (it's RGBA values in one big array): http://jsfiddle.net/zjypd/ (the jsFiddle has an enlarged canvas to show the pixels).

var arr1 = [
    [[255, 255, 255],[200, 200, 0],[]],
    [[200, 0, 0],[200, 200, 0],[200, 200, 0]],
    [[200, 200, 0],[200, 0, 0],[200, 200, 0]]
];

var ctx = document.querySelector("canvas").getContext("2d");

var height = arr1.length;
var width = arr1[0].length;

var h = ctx.canvas.height;
var w = ctx.canvas.width;

var imgData = ctx.getImageData(0, 0, w, h);
var data = imgData.data;  // the array of RGBA values

for(var i = 0; i < height; i++) {
    for(var j = 0; j < width; j++) {
        var s = 4 * i * w + 4 * j;  // calculate the index in the array
        var x = arr1[i][j];  // the RGB values
        data[s] = x[0];
        data[s + 1] = x[1];
        data[s + 2] = x[2];
        data[s + 3] = 255;  // fully opaque
    }
}

ctx.putImageData(imgData, 0, 0);

这篇关于将2维像素阵列复制到Javascript画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆