junikear junikear -4 years ago 76
Javascript Question

JavaScript Canvas crosshair at center

How can I put a canvas crosshair at the center of my canvas.

<canvas id="imageView" width="1400" height="788"></canvas>

The crosshair shall be a drawn one not an image.

Answer Source

Sorry but width="1400" height="788" is too large for this site's snippets, so I changed it in my example.

In the example below change x and y according to your <canvas> width and height devided by 2 (I don't know if you have JQuery or which method you can use to get the width and height).

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

var x = 40;
var y = 20;

var ctx2=c.getContext("2d");

ctx.moveTo(x + 100, y + 10);
ctx.lineTo(x + 100, y + 20);

ctx.moveTo(x + 90, y + 15);
ctx.lineTo(x + 110,y + 15);
<canvas id='myCanvas' style='width:300px;height:300px'></canvas>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download