¿Por qué incPixel no funciona como se esperaba?

<!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>

preguntado el 09 de enero de 11 a las 12:01

1 Respuestas

You're missing the context type parameter from getContext(), it should be:

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

You can test out a demo here with SOLO the change above.

Respondido el 09 de enero de 11 a las 15:01

Thanks, I just noticed. But the result is still the same for me. - tecla inferior

@Joshua - it works in Chrome (see the demo), which browser are you having issues in? - Nick Craver ♦

@Joshua - If it's firefox, that's a error conocido from drawing on a canvas that's smaller. There's a question on how to work-around it here: stackoverflow.com/questions/982000/… - Nick Craver ♦

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.