App下載
首頁javascriptdrawing_settingsCanvas - 如何操縱畫布中的像素

Canvas - 如何操縱畫布中的像素

我們想知道如何操縱畫布中的像素。


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var ctx = canvas.getContext('2d')
var W = 450, H = 450;
canvas.width = W;
canvas.height = H;
rc = function(){
    var rb = function(){
        return Math.floor(Math.random()*255);
    };
    return 'rgb('+rb()+','+rb()+','+rb()+')';
};
for(var i = 0; i < H; i+=10){
    for(var j = 0; j < W; j+=10){
        ctx.fillStyle = rc();
        ctx.fillRect(j,i,10,10);
    }
}
var map = ctx.getImageData(0,0,W,H);
for(var i = 0; i < map.data.length; i+=4){
    map.data[i+0] = 0; // drop red
    //map.data[i+1] = 0; // drop green
    map.data[i+2] = 0; // drop blue
}
ctx.putImageData(map,0,0); // comment this out to see non-green
dl.href = canvas.toDataURL();
}//]]>  
</script>
</head>
<body>
  <a id="dl">Save Image</a>
  <br>
  <canvas id="canvas"></canvas>
</body>
</html>