Feb 21, 2014

Make a Paint in JavaScript (Part 2) - Adapt to Touch Screen



In this post we will adapt the paint you just created for it can be used from any mobile device. If you still have not created the Paint in javascript you can start with this tutorial:


Only we will work on the Javascript file. We have to make some changes:



1 - Add under the mouse events the touch events:


    // When the touch de canavas call the startPaint function
    canvas.addEventListener("touchstart",startPaint,false);
 
    // When the stop touch de canvas call the overPaint function
    canvas.addEventListener("touchend",overPaint,false);



2 - You must add this line within the starPaint() function because its function is that when you open the application with a mobile device and touch the screen it becomes dislodged, and this function eliminates that possibility:



    e.preventDefault();



3 - now, add this line under the "mousemove" event into the starpPaint() function:


    canvas.addEventListener("touchmove",paint,false);



4 - the same than step 3, but into the overPaint() function (under the "mousemove" event):


    canvas.removeEventListener("touchmove",paint,false);



5 - Finaly, you need change the last functions (x_pos, y_pos) as only collect the mouse position, and now need to know if mouse or touch and collect the information from one or another. You need change all the functions


    function x_pos(ev){
if (ev.clientX != null)
{return ev.clientX - canvas.offsetLeft - container.offsetLeft - div_canvas.offsetLeft; }
else
{return ev.targetTouches[0].pageX - canvas.offsetLeft - container.offsetLeft -      div_canvas.offsetLeft; }
     }

     function y_pos(ev){
  if (ev.clientY != null)
  {return ev.clientY- canvas.offsetTop - div_canvas.offsetTop;}
  else
  {return ev.targetTouches[0].pageY - div_canvas.offsetTop;}
    }


that's all!! you have a new paint application in javascript adapt to mobile devices!!!!

Demo

 If you want to see a demo:




This demo has some css styles and some changes in the code but are exclusively design and not vary the implementation of software.

You can find the code in github:




I hope you liked it, and if you have any questions feel free to write me

No comments:

Post a Comment