简体   繁体   English

为什么incPixel无法按预期工作?

[英]Why doesn't incPixel work as expected?

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

You're missing the context type parameter from getContext() , it should be: 你错过了getContext()的上下文类型参数,它应该是:

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

You can test out a demo here with only the change above . 你可以在这里测试一个只有上述变化的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM