2012-10-11

Clickable Swype Canvas by JavaScript and HTML5

Created clickable swype canvas which scrolls window (or IFrame) with plain JavaScript and HTML5. See notes below.
 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
 <title>Clickable Swype Canvas</title>  
 </head>  
 <body>  
 <script type="text/javascript">  
 var active = false;  
 var startX = 0;  
 var startY = 0;  
 function move(e) {  
     if (active) {  
         var dy = (e.clientY - startY);  
         window.scrollBy(0, dy);  
 //         parent.document.getElementById("frame").contentWindow.scrollBy(0, dy);  
     } else {  
         var px = e.clientX - c.offsetLeft;  
         var py = e.clientY - c.offsetTop;  
         if (px > 100 && px < 200) {  
             document.body.style.cursor = "pointer";  
         } else {  
             document.body.style.cursor = "default";  
         }  
     }  
 }  
 function down(e) {  
     active = true;  
     startX = e.clientX - c.offsetLeft;  
     startY = e.clientY - c.offsetTop;  
     ctx.clearRect(0, 0, 200, 1200);  
     ctx.moveTo(0,0);  
     ctx.lineTo(200, 1200);  
     ctx.stroke();  
     ctx.font="30px Arial";  
 //     var scroll = parent.document.getElementById("frame").contentWindow.document.body.scrollTop;  
     var scroll = window.pageYOffset;  
     ctx.fillText("x" + startX + ", y:" + (startY + scroll), 10, 300);  
 }  
 function up(e) {  
     active = false;  
 }  
 function out(e) {  
     active = false;  
 }  
 </script>  
 <canvas id="c" style="background: yellow;" width="200px" height="1200px" onmousemove="move(event);" onmousedown="down(event);" onmouseup="up(event);" onmouseout="out(event);">  
 </canvas>  
 <script>  
 var c = document.getElementById("c");  
 var ctx = c.getContext("2d");  
 ctx.moveTo(0,0);  
 ctx.lineTo(200, 1200);  
 ctx.stroke();  
 </script>  
 </body>  
 </html>  

Notes:

  1. If you want to use IFrame instead, uncomment, remove window.* and create a second page with the IFrame with this one as source. Make sure the id of the IFrame is "frame" or change in this code.
  2. You can make a lot of adjustments regarding the swype. I would add a threshold to the delta x and y to prevent "small" scrolls and to improve click stability.
  3. The canvas is filled with some debug draw to make it easier to see the scroll and click coordinates. This must be added afterwards the canvas tag (?)
  4. Canvas must have width and height, it can't be set in CSS style.
  5. The cursor pointer is changed at some coordinates to demonstrate canvas interaction. Just change the coordinates to some area and make it a link for example (document.location.href="www.google.com";)

Inga kommentarer:

Skicka en kommentar