Unfortunately we don't have any pre-defined method to set pixel color in HTML5 Canvas. In this article I am going to write method to set pixel color.

We can set pixel color by using fillRect method of length of 1 and height of 1. By using fillStyle property we can set color for the pixel.

Here xpos  =  X- Axis,    ypos = Y- Axis, col = Color

function putpixel(xpos,ypos,col) {
  var element = document.getElementById("myCanvas");
  var ctx = element.getContext("2d");
  ctx.fillStyle = col;
  ctx.fillRect( xpos, ypos, 1, 1 );
}

The second approach is setting Image Data for canvas.


Here one pixel has 4 components Red, Green, Blue, Alpha. The whole canvas is single dimensional array. This is why we have to calculate position of the pixel with below formula
                       position of pixel = ( ( row number ) * width * 4 ) + ( column number ) * 4    

JavaScript to set Pixel Color :

function fillColor(width, height, posx, posy, red, green, blue, alpha) {
      var dy = posy * width * 4;
      var pos = dy + posx * 4;
      var element = document.getElementById("myCanvas");
      var ctx = element.getContext("2d");
      var imageData = ctx.getImageData(0, 0, width, height);
      imageData.data[pos++] = red;
      imageData.data[pos++] = green;
      imageData.data[pos++] = blue;
      imageData.data[pos++] = alpha; 
      ctx.putImageData(imageData, 0, 0);      
}

JavaScript to set Pixel Color with Image Data :

function fillColor(imageData,width, height, posx, posy, red, green, blue, alpha) {
      var dy = posy * width * 4;
      var pos = dy + posx * 4;
      imageData.data[pos++] = red;
      imageData.data[pos++] = green;
      imageData.data[pos++] = blue;
      imageData.data[pos++] = alpha; 
}

0 comments:

Blogroll

Follow this blog by Email

Popular Posts