0

I an newbie in html5, I want to create an a dot like image on click event. I try to use context but unfortunately not working. The code that i am using is

 document.addEventListener("DOMContentLoaded", init, false);

      function init()
      {
        var canvas = document.getElementById("options");
        canvas.addEventListener("mousedown", getPosition, false);
      }

      function getPosition(event)
      {
        var x = new Number();
        var y = new Number();
        var canvas = document.getElementById("options");

        if (event.x != undefined && event.y != undefined)
        {
          x = event.x;
          y = event.y;
        }
        else // Firefox method to get the position
        {
          x = event.clientX + document.body.scrollLeft +
              document.documentElement.scrollLeft;
          y = event.clientY + document.body.scrollTop +
              document.documentElement.scrollTop;
        }

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

        alert("x: " + x + "  y: " + y);
           var b_canvas = document.getElementById("b");
    var b_context = b_canvas.getContext("2d");
    b_context.fillRect(50, 25, 150, 100);

Please suggest where I am doing mistake. Give your suggestions

4
  • What does the html that this is interacting with look like? Commented Jun 27, 2012 at 12:22
  • I have an image that i am getting it from xml. and on that i had to apply mouse click event and where i am clicking just dot like image should appear.this is javascript code snippet that i am using to get the coordinates on click Commented Jun 27, 2012 at 12:23
  • It looks like all the calculation is done for canvas with id 'options', but the context is obtained on a canvas with id b. Is that by design? Further in the code sample, x and y are never used for the filling. Perhaps this is a test variant? Commented Jun 27, 2012 at 12:46
  • yes calculations is for options. sorry by mistaken i have written b line their.but still its not working. yes x and y are test variant Commented Jun 27, 2012 at 12:57

1 Answer 1

0

Not sure if that's the problem, but to draw a dot on canvas, you can start a path, draw a completely closed arc (from 0 rad to 2pi rad) and fill that:

     b_context.beginPath();
     b_context.arc(x, y, 5 , 0,  2 * Math.PI,true);
     b_context.fillStyle = "blue";
     b_context.fill();

Further it is important to set width and height directly on canvas and not in css to prevent distortion. (just found that out myself ;) ) Complete example fiddle: http://jsfiddle.net/wHsMJ/ (click inside the rectangle on the right to test)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.