user3411407
user3411407

Reputation: 3

Drawing a circle on HTML5 canvas at touch location

Basically, I'm trying to use JavaScript so when a button is pressed on the page, it will begin listening for the next touch on the canvas. On that touch, a function is triggered which gets the X and Y co-ordinates of the touch and draws a circle there. The circle needs to be labelled as well, so have put in a prompt to get the label. Here is my attempt and a bit of context:

<input type="button" value="Add Symptom" onClick="touch_init();">

When the above input button is pressed the following is triggered:

function touch_init(){
    var canvas = document.getElementById("mediCanvas");
    canvas.addEventListener("touchstart", drawSymptomCircle, false);
}

function drawSymptomCircle(event) {
    var canvas = document.getElementById("mediCanvas");

    if (canvas.getContext){
        var ctx = canvas.getContext("2d");
        var x = new Number();
        var y = new Number();
        var radius = 100;           
        var symptomName=prompt("Please enter the name of your symptom:");

        x = event.targetTouches[0].pageX;
        y = event.targetTouches[0].pageY;

        x-=canvas.offsetLeft;
        y-=canvas.offsetTop;

        ctx.beginPath();
        ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
        ctx.fillStyle = "rgb(0,128,255)";
        ctx.fill();
        ctx.lineWidth = 2;
        ctx.strokeStyle = "black";
        ctx.stroke();

        ctx.font = '15pt Calibri';
        ctx.fillStyle = 'black';
        ctx.textAlign = 'center';
        ctx.fillText(symptomName, x, y);

        canvas.removeEventListener("touchstart", drawSymptomCircle, false);
     }
}

EDIT: This draws circles actually inside the canvas, not just at 0,0 , but they are not drawn in the right places. Why are they are not in the correct place?

Upvotes: 0

Views: 1339

Answers (1)

user1693593
user1693593

Reputation:

Use clientX/Y instead and use bounding rect to compensate for canvas position:

function drawSymptomCircle(event) {

    var canvas = this;  // no need to get canvas element from DOM, this = canvas

    if (canvas.getContext){  // this test should be done once in global, not here :)
        ...

        var rect = this.getBoundingClientRect();  // absolute position of canvas
        x = event.targetTouches[0].clientX;       // relative to client win
        y = event.targetTouches[0].clientY;

        x -= rect.left;                           // adjusted to be relative to canvas
        y -= rect.top;

        ...

Also obtaining getContext() is something I would recommend you do in global/parent scope. this will represent the canvas element as the element is the default context for an event handler.

Upvotes: 1

Related Questions