canvas简单操作图片像素颜色

2023-08-03  本文已影响0人  IamaStupid

canvas简单操作图片像素颜色

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>canvas</title>
    <style type="text/css">
      body {
        padding: 0; margin: 0; width: 100%; height: 100%;
      }
      canvas {
        background-color: #000;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas"></canvas>
    <!-- built files will be auto injected -->
    <script>
      var $cvs=document.getElementById("myCanvas");
      var ctx=$cvs.getContext("2d");

      let ww = 700;
      let hh = 700;

      $cvs.width = ww;
      $cvs.height = hh;

      drawImg()

      function drawImg() {
        let img = new Image();
        img.onload = function() {
          // 从图片的(0,0)开始,裁剪宽度500,高度300的区域
          // 将裁剪的贴图,放到canvas里面(5,5)的位置,拉伸贴图的宽高为200*200
          // canvas里面(5,5)的位置是必填字段,如果参数只有一组,前面两组【0,0,500,300】的参数会使用默认值【0,0,100%, 100%】
          ctx.drawImage(img, 0, 0, 500, 300, 5, 5, 200, 200 );

          var imgData=ctx.getImageData(5,5,200,200);

          console.log(imgData)
          let row = 0;
          let col = 0;
          let groupNum = 4;
          for(let i = 0; i < imgData.data.length; i = i + 4) {
            // 四个元素是一组,表示一个元素 rgba
            let r = imgData.data[i];
            let g = imgData.data[i + 1];
            let b = imgData.data[i + 2];
            let a = imgData.data[i + 3];
            col++;
            // 现在改变图片每行,中间一个像素的颜色
            if (col === imgData.width / 2 || col === 1) {
              imgData.data[i] = 255 - r;
              imgData.data[i + 1] = 255 - g;
              imgData.data[i + 2] = 255 - b;
              imgData.data[i + 3] = a;
            } else if(col === imgData.width) {
              row++
              col = 0;
            }
          }

          ctx.putImageData(imgData,220,220);
        }
        img.src = './images/123.jpg'
      }
    </script>

  </body>
</html>

上一篇下一篇

猜你喜欢

热点阅读