0
    function Shooter(shooter)
{
    shooter.parent.style.width = "300px";
    shooter.parent.style.height = "200px";
    shooter.parent.style.border = "1px solid";
    shooter.parent.style.border.borderColor = shooter.borderColor;


    var canvas = document.createElement("canvas");

    canvas.style.width = "300px";
    canvas.style.height = "200px";

    canvas.addEventListener('mousedown', drawBullet, false);    

    shooter.parent.appendChild(canvas);
}

function drawBullet(event){
    var rect = this.getBoundingClientRect();

    var x = event.clientX - rect.left;
    var y = event.clientY - rect.top;

    var ctx = this.getContext("2d");

    console.log(this);
    console.log(x,y);
    console.log(event.clientX, event.clientY);

    ctx.fillStyle = "#ff2626"; // Red color
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, Math.PI * 2);
    ctx.fill();
}

Trying to draw an arc at mouse position after creating the canvas dynamically, for example: pressing on the bottom right of the canvas gives me the correct position but doesn't draw arc where pressed, pressing on the middle will draw arc away from the mouse position. checked for solutions and tried different widths and heights, if the canvas size is 250x100 it almost draws the correct arcs positions.

  • The HTML code contains the script and only a body with a class.
HT K
  • 3
  • 1
  • 2

1 Answers1

0

Use

canvas.width = 300;
canvas.height = 200;

instead of

canvas.style.width = "300px";
canvas.style.height = "200px";

Why?

By default the canvas width property is set to 300 and it's height to 150. The context will only operate within those dimensions. Setting the canvas' CSS height and width will only scale it to the specified size, meaning that your arc gets drawn within a 300x150 box and then stretched to 300x200. This leads to distortion and inaccurate positioning.

Demo

Mathias
  • 41
  • 1
  • 4