【发布时间】:2017-10-16 05:47:15
【问题描述】:
在 Brick Breaker 游戏开始时,玩家使用鼠标瞄准球。当您左键单击鼠标时,它将向该方向移动球。如何创建一条线来指示球的目标位置。我尝试查找有关如何执行此操作的示例,但找不到任何内容。
当我输入ctx.lineTo(cursorX, cursorY); 时,什么都没有显示,但是当我输入ctx.lineTo(100, 100); 时,它会划清界限。我是否需要一个动画函数,以便它在新的cursorX 和cursorY 的位置绘制线条?
我的代码:
<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>
【问题讨论】:
-
创建行的哪一部分让您感到困惑?如何获得终点?或者如何实际绘制该死的东西?
标签: javascript canvas onmousemove