【问题标题】:Problem with element positioning in JS / HTMLJS / HTML 中的元素定位问题
【发布时间】:2022-11-18 10:53:27
【问题描述】:

我需要帮助来制作一条从游戏中心指向鼠标光标的光线,但顶部和左侧的偏移存在问题。这条线在鼠标附近的某个地方,我不明白它与什么相连。网站:https://moomoo.io

Debug video

代码:

let line = document.createElement('div');
line.id = 'line';
document.body.appendChild(line);
let x = 0;
let y = 0;
document.querySelector('html').onmousemove = function(event) { // I wrote in the html selector so you can run here. There should be a gameCanvas
  event = event || window.event;
  console.log(event.offsetX, event.offsetY);
  x = event.offsetX;
  y = event.offsetY;
}
let canvas = document.getElementById('gameCanvas')
setInterval(function draw_line() {
  delta_x = x - (document.documentElement.clientWidth / 2);
  delta_y = y - (document.documentElement.clientHeight / 2);
  theta_radians = Math.atan2(delta_y, delta_x);
  console.log(theta_radians);
  line.setAttribute('style', `border: 2px solid lime; width: 200px; -webkit-transform: rotate(${theta_radians}rad); position: absolute; top: ${y}px; left: ${x}px; height: 0`);
}, 1);

【问题讨论】:

    标签: javascript css


    【解决方案1】:

    您是否考虑过在屏幕顶部添加一个新画布并像那样绘制它?

    控制尚未转换/翻译的画布要容易得多。

    我写了一个示例脚本,我认为它应该可以正常工作。

    let canvas = document.createElement('canvas');
    
    let styles = {
        width: '100%',
        height: '100%',
        position: 'absolute',
        top: 0,
        left: 0,
        zIndex: 9999,
        pointerEvents: 'none'
    }
    
    Object.assign(canvas.style, styles);
    
    document.body.appendChild(canvas);
    
    let ctx = canvas.getContext('2d');
    
    let width = window.innerWidth;
    let height = window.innerHeight;
    
    canvas.width = width;
    canvas.height = height;
    
    let centerX = width / 2;
    let centerY = height / 2;
    let mouseX = 0;
    let mouseY = 0;
    
    window.addEventListener('mousemove', (e) => {
        ctx.clearRect(0, 0, width, height);
        mouseX = e.clientX;
        mouseY = e.clientY;
        ctx.beginPath();
        ctx.moveTo(mouseX, mouseY);
        ctx.lineTo(centerX, centerY);
        ctx.stroke();
    });
    

    【讨论】:

      猜你喜欢
      • 2019-07-27
      • 1970-01-01
      • 2011-05-27
      • 2014-08-16
      • 2015-09-13
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多