Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/425.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使画布元素面向鼠标指针_Javascript_Html5 Canvas - Fatal编程技术网

Javascript 如何使画布元素面向鼠标指针

Javascript 如何使画布元素面向鼠标指针,javascript,html5-canvas,Javascript,Html5 Canvas,我目前正在学习html5画布,我正在制作一个程序,可以旋转一个三角形来面对鼠标所在的位置。它部分工作,但跳过了一半,我想知道是否有更好的方法来完成它,以及我当前的代码有什么问题 谢谢 const ctx = document.getElementById("canvas").getContext("2d") ctx.canvas.style.backgroundColor = "#303030" ctx.canvas.width = 500 ctx.canvas.height = 500 c

我目前正在学习html5画布,我正在制作一个程序,可以旋转一个三角形来面对鼠标所在的位置。它部分工作,但跳过了一半,我想知道是否有更好的方法来完成它,以及我当前的代码有什么问题

谢谢

const ctx = document.getElementById("canvas").getContext("2d")
ctx.canvas.style.backgroundColor = "#303030"

ctx.canvas.width = 500
ctx.canvas.height = 500

const w = ctx.canvas.width
const h = ctx.canvas.height

let x = 0;
let y = 0;

let degrees = 0;

triAngle = 60

ctx.canvas.addEventListener("mousemove", mouseMove, false)

function mouseMove(evt) {
    x = evt.clientX
    y = evt.clientY

    let diffX = x - w / 2;
    let diffY = y - h / 2;

    console.log(diffX, diffY)

    degrees = Math.floor(Math.atan(diffY / diffX) * 57.2958);

    //Math.atan(diffY/ diffX)
    console.log(degrees)
}

function draw() {
    debugger ;
    ctx.clearRect(0, 0, w, h)

    ctx.fillStyle = "#fff";

    ctx.save()
    ctx.translate(w / 2, h / 2)
    ctx.rotate(degree(degrees + triAngle / 2))
    ctx.beginPath()
    ctx.moveTo(0, 0)
    ctx.lineTo(0, 100)
    ctx.rotate(degree(triAngle))
    ctx.lineTo(0, 100)
    ctx.closePath()
    ctx.fill()
    ctx.restore()

    requestAnimationFrame(draw)
}

function degree(input) {
    return Math.PI / 180 * input
}

draw()

跳过一半方向的原因是因为分数的符号。圆有四个象限,从{x:0,y:0}到{x:1,y:1},{x:-1,y:1},{x:-1,y:-1}和{x:1,y:-1}的直线只产生两个值1,如果你将y除以x,例如1/1==1,1/-1=-1,-1/1=-1,和-1/-1==1,那么无法知道这两个象限中的哪个值是1和-1

可以使用以弧度为单位获取从一点到另一点的角度。在-Math.PI到Math.PI-180度到180度的范围内

顺便说一句,没有必要将弧度转换为deg,因为JavaScript中的所有数学函数都使用弧度

requestAnimationFramemainLoop; const ctx=canvas.getContext2d canvas.height=canvas.width=300; canvas.style.backgroundColor=303030; 常数鼠标={x:0,y:0}; canvas.addEventListenermousemove,e=>{ mouse.x=e.clientX; mouse.y=e.clientY; }; 常量形状={ 颜色:青柠, x:150, y:150, 尺码:50, 路径:[1,0,-0.5,0.7,-0.5,-0.7], }; 函数拉伸形状{ var i=0; 常数s=shape.size,p=shape.path; ctx.fillStyle=shape.color; const rot=Math.atan2mose.y-shape.y,mouse.x-shape.x; const xa=Math.cosrot; const ya=Math.sinrot; ctx.xa,ya,-ya,xa,shape.x,shape.y; ctx.beginPath; 而i