javascript图像处理框架

</pre><pre name="code" class="html"><!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>canvas图像处理</title>
</head>
<body>
    <h1>canvas</h1>
    <canvas id="canvas1" width="100" height="100">绘图区域</canvas>




    <script type="text/javascript">
        var canvas1 = document.getElementById("canvas1");
        var context1 = canvas1.getContext('2d');
        image = new Image();
        image.src = "z.bmp";
        image.onload = function () {
            context1.drawImage(image, 0, 0); //绘制原始图像,(0,0)表示图像的左上角位与canvas画布的位置
        }


    </script>
    <br />
    <button onclick="RGB2GRAY()">彩色转灰度</button>
<br />
<canvas id="canvas2" width="100" height="100"></canvas>
    <script>
       

        //彩色转灰度
        function RGB2GRAY() {
            var canvas2 = document.getElementById('canvas2');
            var context2 = canvas2.getContext('2d');
            var imagedata = context1.getImageData(0, 0, image.width, image.height);
            //getImageData(x1,y1,x2,y2)获取图像的rgba矩阵,其中截取图像的大小为(x1,y1)-(x2,y2) 的矩阵
            var imagedata1 = context2.createImageData(image.width, image.height);
            //createImageData(x,y):创建宽高分别为x,y的图像矩阵
            for (var j = 0; j < image.height; j += 1)
                for (var i = 0; i < image.width; i += 1) {
                    k = 4 * (image.width * j + i);
                    var temp = imagedata.data[k + 0] * 0.299 + imagedata.data[k + 1] * 0.587 + imagedata.data[k + 2] * 0.114;
                    imagedata1.data[k + 0] = temp;
                    imagedata1.data[k + 1] = temp;
                    imagedata1.data[k + 2] = temp;
                    imagedata1.data[k + 3] = 255;
                }
            context2.putImageData(imagedata1, 0, 0);
        }
 </script>
</body>
</html>
在工程目录下需放置一张z.bmp的图片。画布大小可调整。框架就这样了,要实现其他功能可以照葫芦画瓢。


版权声明:

posted on 2015-03-04 10:29  moffis  阅读(353)  评论(0编辑  收藏  举报

导航