Canvas How to - Set pixel on Canvas








Question

We would like to know how to set pixel on Canvas.

Answer


<!--  w w w  .  j a va2s.  c o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<style type='text/css'>
canvas {
  margin: 1em;
  border: 1px solid #dddddd;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
var element,
    canvas,
    width,
    height,
    red;
black = {
    r: 0,
    g: 0,
    b: 0,
    a: 255
};
// init canvas
element = $('#canvas').get(0);
canvas = element.getContext('2d');
width = element.width;
height = element.height;
canvas.fillStyle = '#eeeeee';
canvas.fillRect(0, 0, width, height);
// setpixel
var setPixel = function (x,y,c) {
    var p=canvas.createImageData(1,1);
    p.data[0]=c.r;
    p.data[1]=c.g;
    p.data[2]=c.b;
    p.data[3]=c.a;
    canvas.putImageData(p,x,y);
}
$('#canvas').on('click',
function (e) {
    setPixel(e.offsetX, e.offsetY, black);
});
});//]]>  
</script>
</head>
<body>
    <p>Click to set pixel</p>
  <canvas id='canvas' width='128' height='128'></canvas>
</body>
</html>

The code above is rendered as follows: