1. 程式人生 > >canvas和svg

canvas和svg

new gre 空白 spl wid req r++ none 設置

1. canvas進行像素級操作

獲取一塊像素 => "數組"; let imageData = getImageData(x,y,w,h) (imageData是一個對象,包括‘data‘, ‘width‘, ‘height‘ 三個屬性)
設置一塊像素 => "數組"->Canvas; putImageData(imageData)
創建一塊像素 => 空白數組

一個像素占4位:rgba
r 0~255
g 0~255
b 0~255
a 0~255

應用:比如將圖片色調點黃

 <script>
    window.onload
=function (){ let oC=document.getElementById(‘c1‘); let gd=oC.getContext(‘2d‘); let W=oC.width,H=oC.height; let oImg=new Image(); oImg.src=‘http://127.0.0.1:8080/www/2.jpg‘; oImg.onload=function (){ gd.drawImage(oImg, 0, 0); let imageData=gd.getImageData(0, 0, W, H);
//黃=>扔掉藍色 for(let r=0;r<H;r++){ for(let c=0;c<W;c++){ //(r*W+c)*4+0 => red //(r*W+c)*4+1 => green //(r*W+c)*4+2 => blue //(r*W+c)*4+3 => alpha imageData.data[(r*W+c)*4+2]=0; } }
// gd.putImageData(imageData, 0, 0); }; }; </script>

2.video處理,對視頻的每一幀進行處理

<script>
    window.onload=function (){
      let oV=document.getElementById(‘v1‘);
      let oC=document.getElementById(‘c1‘);
      let gd=oC.getContext(‘2d‘);

      let W=oC.width,H=oC.height;

      requestAnimationFrame(next);

      function next(){
        gd.drawImage(oV, 0, 0);

        //
        let imageData=gd.getImageData(0, 0, W, H);
        let data=imageData.data;

        for(let r=0;r<H;r++){
          for(let c=0;c<W;c++){
            data[(r*W+c)*4+0]=data[(r*W+c)*4+1]=data[(r*W+c)*4+2]=
            (data[(r*W+c)*4+0]+data[(r*W+c)*4+1]+data[(r*W+c)*4+2])/3;
          }
        }

        gd.putImageData(imageData, 0, 0);

        requestAnimationFrame(next);
      }
    };
    </script>
  </head>
  <body>
    <video src="movie.ogg" id="v1" autoplay loop style="display:none;"></video>
    <canvas id="c1" width="320" height="240"></canvas>
  </body>

3.

canvas和svg