为什么incPixel不按预期工作?

时间:2011-01-09 12:27:34

标签: javascript jquery html5 canvas

<!DOCTYPE html>
<html>
  <head>
    <meta lang="EN" />

    <script type="text/javascript" src="jquery-1.4.4.min.js"></script>
    <script type="text/javascript">

// Don't resize the window    

function _(str){
    return document.getElementById(str);
}

function incPixel(imageData, x, y){
    var index = (x + y * imageData.width) * 4;
    imageData.data[index + 0] = 155;
    imageData.data[index + 1] = 155;
    imageData.data[index + 2] = 155;
    imageData.data[index + 3] = 155;
}

$(document).ready(function(){
    // collect mouse position data
    var history = [];
    $(document).mousemove(function(e){
 history.push([e.pageX, e.pageY]);
    });

    // when the button is clicked
    $("#button").click(function(){
 // 1. disable mouse position data collection
 $(document).unbind("mousemove");

 // 2. draw pixels on the canvas
 var width = $(document).width();
 var height = $(document).height();

 $("#canvas").height(height).width(width);

 var canvas = document.getElementById("canvas");

 if(canvas.getContext){
     var context = canvas.getContext("2d");

     var imageData = context.createImageData(width, height);

     for(var i=0; i<history.length; i++){
         incPixel(imageData, history[i][0], history[i][1]);
     }

     context.putImageData(imageData, 0, 0);
     alert(JSON.stringify(history));
 }else{
     alert("no context");
 }
    });
});

    </script>
  </head>

  <body>
    <h1>Hello, Worlds!</h1>
    <div id="width"></div>
    <div id="height"></div>
    <input type="button" id="button" value="Click me" /><br />

    <canvas id="canvas" />
  </body>
</html>

1 个答案:

答案 0 :(得分:2)

您错过了getContext()中的上下文类型参数,它应该是:

var context = canvas.getContext('2d');

You can test out a demo here with only the change above