www.webdeveloper.com
Results 1 to 3 of 3

Thread: Clickable image object on canvas tag?

  1. #1
    Join Date
    Dec 2010
    Posts
    63

    Clickable image object on canvas tag?

    I'm open for any solutions/ideas. I want to be able to place an image on the canvas and have an onclick event for that object.

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    	<title> Canvas test </title>
    
    	<script>
    	
    	var $ = function(id) { return document.getElementById(id); }
    		
    	</script>
    	
    	</head>
    	<body>
    	<canvas id="e" height="500" width="500"></canvas>
    	
    <script>
      var canvas = document.getElementById("e");
      var context = canvas.getContext("2d");
      var face = new Image();
      face.src = "http://showellblades.com/wp-content/uploads/2006/10/smiley_face.jpg";
    
      
      face.onload = function() {
        context.drawImage(face, 0, 0);
    
      };
    
    </script>
    	</body>
    </html>

  2. #2
    Join Date
    Jun 2007
    Location
    Washington D.C. Metro
    Posts
    76
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    	<title> Canvas test </title>
    
    	<script>
    	
    	var $ = function(id) { return document.getElementById(id); }
    		
    	</script>
    	
    	</head>
    	<body>
    	<canvas id="e" height="500" width="500"></canvas>
    	
    <script>
      var canvas = document.getElementById("e");
      var context = canvas.getContext("2d");
      var face = new Image();
      face.src = "http://showellblades.com/wp-content/uploads/2006/10/smiley_face.jpg";
    	
      face.onload = function() {
        context.drawImage(face, 0, 0);
      };
    
      canvas.addEventListener("click", onCanvasClick, false);
      
      function onCanvasClick(e) {
      	alert(getCursorPosition(e));
      }
      
      function getCursorPosition(e) {
      	var x;
        var y;
        if (e.pageX != undefined && e.pageY != undefined) {
    	x = e.pageX;
    	y = e.pageY;
        }
        else {
    	x = e.clientX + document.body.scrollLeft +
                document.documentElement.scrollLeft;
    	y = e.clientY + document.body.scrollTop +
                document.documentElement.scrollTop;
        }
        x -= canvas.offsetLeft;
        y -= canvas.offsetTop;
        
        return [x,y];
      }
    
    </script>
    	</body>
    </html>
    then you can determine how to process the coordinates from there

  3. #3
    Join Date
    Dec 2010
    Posts
    63
    This is great!! Thanks a ton

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles