HTML5 Game - Get color from an image pixel

Description

Get color from an image pixel

Demo

ResultView the demo in separate window

<!DOCTYPE html>

<html>
<head>
<title>Manipulating images and video</title>
<meta charset="utf-8">

<script type="text/javascript"
  src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script type="text/javascript">
  $(document).ready(//  ww w  . java  2s. c o  m
      function() {
        let canvas = $("#myCanvas");
        let context = canvas.get(0).getContext("2d");


        let image = new Image();
        image.src = "http://java2s.com/style/demo/jet2.png";
        $(image).load(function() {
          context.drawImage(image, 0, 0, 500, 333);
        });

        canvas.click(function(e) {
          let canvasOffset = canvas.offset();
          let canvasX = Math.floor(e.pageX - canvasOffset.left);
          let canvasY = Math.floor(e.pageY - canvasOffset.top);

          let imageData = context.getImageData(canvasX, canvasY, 1, 1);
          let pixel = imageData.data;
          let pixelColour = "rgba(" + pixel[0] + ", " + pixel[1]+ ", " + pixel[2] + ", " + pixel[3] + ")";

          $("body").css("backgroundColor", pixelColour);
        });
      });
</script>
</head>

<body>
  <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
  </canvas>
</body>
</html>

Related Topic