Search code examples
javascripthtmltouchcolor-picker

How do i change from mouse to touch instead?


I uses canvas to create a color picker, and able to get the color code but when i use it in mobile form , i only can tap to choose color. How to i change the code so that when in mobile i can use my finger and drag along the canvas to choose color?

var canvas = document.getElementById("picker");
var context = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 100;
var counterClockwise = false;

for(var angle=0; angle<=360; angle+=1){
    var startAngle = (angle-2)*Math.PI/180;;
    var endAngle = angle * Math.PI/180;
    context.beginPath();
    context.moveTo(x, y);
    context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
    context.closePath();
    context.fillStyle = 'hsl('+angle+', 100%, 50%)';
    context.fill();
}


function createColorWheel(){
    var ctx = document.getElementById('picker').getContext('2d');
   ctx.canvas.addEventListener('mousemove',function(e){
       // Set the offset for canvas x and y                                           
    var X =  e.clientX - ctx.canvas.offsetLeft;
       var Y = e.clientY - ctx.canvas.offsetTop;
    // Get Image Data Object of pixel currently under crosshair
    var imageData = ctx.getImageData(X, Y, 1, 1);
    // Set pixel to the data array (r, g, b, a)
       var pixel = imageData.data; 
    // Add leading zero to number
    // Convert  number to a hexadecimal string with .toString(16)
    // Get the last 2 digits of that string with .slice
    var r = ("0" + (pixel[0]).toString(16)).slice(-2);
    var g = ("0" + (pixel[1]).toString(16)).slice(-2);
    var b = ("0" + (pixel[2]).toString(16)).slice(-2);
    htmlHex = "#"+r+g+b;
    // Change background color of the canvas as the mouse moves
    var previewColor = document.getElementById('picker').style.background = htmlHex;
   });        
}

window.onload = createColorWheel; 

Solution

  • The problem is that mobile device would fire touch event instead of mouse event. In your case, you should use touchmove event on mobile device.

    You may make your code works for touch event by changing the event listener. Be noted that touch position is retrieved using the changedTouches property.

    ctx.canvas.addEventListener('touchmove',function(e){                                  
        var X =  e.changedTouches[0].clientX - ctx.canvas.offsetLeft;
        var Y = e.changedTouches[0].clientY - ctx.canvas.offsetTop;
        //........
    

    If you need the code to work for multiple platforms, you may need to do some more coding to handle different events on different platforms.

    A simple solution to handle cross platform event is to use jQueryMobile. It has a vmousemove event which will take care of the cross platform issue.