我的代码有什么问题,为什么它没有在画布上实现颜色?

时间:2018-03-04 16:40:30

标签: javascript canvas

这是我的JavaScript代码:

function setColor(){

   var x=document.getElementById('canvas');
   var ctx = x.getContext('2d');
   var pixel = ctx.getImageData(0, 0, 1, 1);
   //var data = pixel.data;

   //var clrss = 'rgb(255, 0, 0)';
   for (var i = 0; i < pixel.data.length; i+=4) {

          //red
          pixel.data[i] = 230;
          // green
          pixel.data[i + 1] = 170;
          // blue
          pixel.data[i + 2] = 255;
          //alpha
          //data[i + 3] = 0;
console.log("blue");
        }

        // overwrite original image
        ctx.putImageData(pixel, 0, 0);
      }

这是我的HTML代码:

<canvas id="canvas"></canvas><br>
<img id="PM" src="PM.png">
<input type="button" onclick="setColor();" value="BTest">

1 个答案:

答案 0 :(得分:0)

您尚未设置画布的大小:

<canvas id="canvas" width="1" height="1"></canvas><br>
<img id="PM" src="PM.png">
<input type="button" onclick="setColor();" value="BTest">