create an Image object from an ImageData object? - Javascript Canvas

Javascript examples for Canvas:image

Description

create an Image object from an ImageData object?

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <!-- reset css --> 
      <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> 
      <style>

canvas{border:1px solid red;}

      </style> 
      <script>
$(function(){/*w w  w. jav a 2s .c  om*/
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    // draw a red rect on the canvas
    ctx.fillStyle="red";
    ctx.fillRect(50,50,75,40);
    // get the canvas imageData
    var imageData=ctx.getImageData(0,0,canvas.width,canvas.height);
    var data=imageData.data;
    // replace any red pixels with green pixels
    for(var i=0;i<data.length;i+=4){
        if(data[i]>250){
            data[i]=0;
            data[i+1]=255;
        }
    }

    ctx.clearRect(0,0,canvas.width,canvas.height);

    var tempCanvas=document.createElement("canvas");
    var tempCtx=tempCanvas.getContext("2d");
    tempCanvas.width=canvas.width;
    tempCanvas.height=canvas.height;

    tempCtx.putImageData(imageData,0,0);

    var img=new Image();
    img.onload=function(){

        ctx.drawImage(img,0,0);
    }
    img.src=tempCanvas.toDataURL();
}); // end $(function(){});

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" width="300" height="300"></canvas>  
   </body>
</html>

Related Tutorials