Can't get Three.js onDocumentMouseDown to work correctly

后端 未结 2 1778
再見小時候
再見小時候 2020-12-22 05:57

I\'ve looked at a lot of examples -- and borrowed from some -- and can\'t seem to get this to work right. What I want is for the raycaster in onDocumentMouseDown to pick up

相关标签:
2条回答
  • 2020-12-22 06:10

    In your makeTextSprite() function, after

    var textWidth = metrics.width;
    

    add this

    context.strokeStyle = "white";
    context.lineWidth = 5;
    context.strokeRect(0,0,canvas.width, canvas.height);
    

    and you will see, that your sprites have not the size you think of.

    UPD. You can set the size of a canvas like this

    var ctxFont = "bold " + fontsize + "px " + fontface;
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    context.font = ctxFont;
    var metrics = context.measureText(message);
    var textWidth = metrics.width;
    
    canvas.width = textWidth + borderThickness * 2;
    canvas.height = fontsize * 1.2 + (borderThickness * 2);
    context = canvas.getContext('2d');
    context.font = ctxFont;
    

    and then set the scale of a sprite

    sprite.scale.set(canvas.width / 10, canvas.height /  10, 1);
    

    jsfiddle example

    0 讨论(0)
  • 2020-12-22 06:19

    Your Three.js canvas probably isn't at the top left of the screen, and you're not taking into account the offset from 0,0 on the page. To fix it, adjust the mouse position to subtract the offset.

    var rect = container.getBoundingClientRect();
    mouse.x = ((event.clientX - rect.left) / renderer.domElement.clientWidth) * 2 - 1;
    mouse.y = -((event.clientY - rect.top) / renderer.domElement.clientHeight) * 2 + 1;
    
    0 讨论(0)
提交回复
热议问题