At the start of a Brick Breaker game, the player aims the ball using the mouse. When you left click the mouse, it will move the ball in that direction. How do I create a line that will indicate where the ball is aiming. I tried looking up examples on how to do it but couldn't find anything.
When I put ctx.lineTo(cursorX, cursorY);
nothing shows, but when I put ctx.lineTo(100, 100);
it draws the line. Do I need an animate function so that it draws the line at the location at the new cursorX
and cursorY
?
My Code:
<html>
<script type="text/javascript">
window.onload = init;
function init() {
if (window.Event) {
document.captureEvents(Event.MOUSEMOVE);
}
document.onmousemove = getCursorXY;
drawLine();
}
function getCursorXY(e) {
cursorX = document.getElementById('cursorX').value = (window.Event)
? e.pageX
: event.clientX + (document.documentElement.scrollLeft
? document.documentElement.scrollLeft
: document.body.scrollLeft);
cursorY = document.getElementById('cursorY').value = (window.Event)
? e.pageY
: event.clientY + (document.documentElement.scrollTop
? document.documentElement.scrollTop
: document.body.scrollTop);
}
function drawLine() {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(cursorX, cursorY);
ctx.stroke();
}
</script>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<input type="text" id="cursorX" size="3"> X-position of the mouse cursor
<br /><br />
<input type="text" id="cursorY" size="3"> Y-position of the mouse cursor
</body>
</html>