画布 - 如何从远处

时间:2017-01-10 15:29:13

标签: javascript canvas html5-canvas

我一直致力于这个可以将枪移向光标所在位置的游戏。但是,我所要做的就是:

<!doctype html>
<html>
    <head>
        <title>Block Shooter</title>
    </head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <body>
        <center>
            <canvas id="canvas" width="1200" height="600" style="border: 1px solid black"></canvas>
            <script>
            // Variables

            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            var start = false;
            var gunWidth = 80;
            var gunLength = 150;

            $("#canvas").mousemove((event) => {
                ctx.clearRect(0, 0, canvas.width, canvas.height)
                ctx.beginPath();
                ctx.lineWidth = gunWidth;
                ctx.strokeStyle = "black";
                //get dimensions of canvas. 
                var dimensions=event.target.getBoundingClientRect();
                var middle=dimensions.left+(dimensions.width/2)
                ctx.moveTo(canvas.width / 2, canvas.height);
                //get mousex relative to canvas
                var mousex=event.offsetX
                //get mousey relative to canvas 
                var mousey=event.offsetY

                var ydistance=mousey;
                var xdistance=mousex-middle
                //distance formula 
                var distance=Math.sqrt((xdistance*xdistance)+(ydistance*ydistance))

                var gunlength=200;
                var drawx=(gunlength*(xdistance/distance))+middle
                var drawy=gunlength*(ydistance/distance)

                ctx.lineTo(drawx, drawy);

                ctx.stroke();
                ctx.closePath();

            })

            </script>
        </center>
    </body>

</html>

现在,不知怎的,它没有正确指向并停止移动。这有解决方案吗?请举个例子。谢谢!

1 个答案:

答案 0 :(得分:3)

如果您按照maths described herehere进行操作,那么最终会得到如下代码:

const x0 = canvas.width * 0.5;
const y0 = canvas.height;

const x1 = event.offsetX;
const y1 = event.offsetY;

const distance = Math.sqrt(((x1 - x0) * (x1 - x0)) + ((y1 - y0) * (y1 - y0)));

const t = gunLength / distance;
const x = ((1 - t) * x0) + (t * x1);
const y = ((1 - t) * y0) + (t * y1);

ctx.lineTo(x, y);

Here's the fiddle.