dinsdag 15 november 2011

How to implement touch events on Canvas...

c.addEventListener("touchmove", on_touchmove, false);
c.addEventListener("touchstart", on_touchstart, false);
c.addEventListener("touchend", on_touchend, false);
...


var clicked = false;


function on_touchstart(ev) {
ev.preventDefault();
        Mouse.x = ev.touches[0].pageX;
        Mouse.y = ev.touches[0].pageY;
cliced = true;




}


function on_touchmove(ev) {
ev.preventDefault();
    Mouse.x = ev.touches[0].pageX;
    Mouse.y = ev.touches[0].pageY;
}




function on_touchend(ev){
clicked = false;
}

zaterdag 5 november 2011

Finally I've solved the problem of scaling Canvas on Android . When letting Android do the scaling, canvas acts like a webbrowser with the images bluring everytime the screen is touched - very ugly! So I decided to make canvas do all the scaling. My first thought was to simply use ctx.scale(x,y), but that didn't work as expected, it only rescaled the coordinates, drawing only partial images on the canvas. So then I tried calculating the scaling factor with Javascript. This turned out to be a headache and why? After endless tries I found out what I was starting to suspect.. the issue reported here - document.width returns different screen widths on each run. The solution is to simply use a setTimeout on startup. Having found this out, all I had to do was write some custom drawImage, fillText en fillRect functions. Maybe I'll try to prototype these functions later to save time writing apps in the future. But for now here is my code:

var c,ctx;
var s;

function start(){
setTimeout(init,500); //A shorter timeout would probably do, but just to be safe.
}
function init(){
    c=document.getElementById("canvas");
    ctx=c.getContext("2d");
   
    c.setAttribute("width", document.width );
    c.setAttribute("height",document.height );
    s = document.width / 800;
    ...
}
function drawImg(img, sx, sy, sw, sh, dx, dy, dw, dh){
    ctx.drawImage(img, sx, sy, sw, sh, dx*s, dy*s, dw*s, dh*s);
}

dinsdag 1 november 2011