javascript - Correct Mouseposition on element while using CSS aspect ratio -
i have canvas scales 16:9 aspect ratio. mouse not take offset (black background) account.
the dotted green line marks canvas. @ edge mouse should display: mouse : 0% | 23% rather mouse : 7% | 23%.

the problem seems occur here:
var x = math.floor( mouse.x / canvas.width * 100 ); var y = math.floor( mouse.y / canvas.height * 100 ); it works fine when go fullscreen mode. (because there no offset) otherwise not take offset account.
additional code:
css:
#aspectoverlay { /* 16:9 */ width: 100vw; height: 56.25vw; /* 100/56.25 = 1.778 */ border: 1px #afff00 dashed; max-height: 100vh; max-width: 177.78vh; /* 16/9 = 1.778 */ margin: auto; position: absolute; top:0;bottom:0; /* vertical center */ left:0;right:0; /* horizontal center */ z-index: 100; opacity: 1; } js:
var canvas = document.getelementbyid('aspectoverlay'); canvas.width = window.innerwidth; canvas.height = window.innerheight; var ctx = canvas.getcontext('2d'); window.addeventlistener('resize', resizecanvas, false); function resizecanvas () { canvas.width = window.innerwidth; canvas.height = window.innerheight; } canvas.addeventlistener('mousemove', function(e){ mouse.x = e.x; mouse.y = e.y; }); var x = math.floor( mouse.x / canvas.width * 100 ); var y = math.floor( mouse.y / canvas.height * 100 ); ctx.filltext("mouse : " + x + "% | " + y + "%", 50,50);
you need take offsets of element account so
mouse.x = e.x - this.offsetleft; mouse.y = e.y - this.offsettop; and since using css resize , setting canvas innerheight , width, can't use canvas width , height calculations anymore need use offsetwidth , offsetheight
var x = math.floor(mouse.x / canvas.offsetwidth * 100); var y = math.floor(mouse.y / canvas.offsetheight * 100); var canvas = document.getelementbyid('aspectoverlay'); canvas.width = window.innerwidth; canvas.height = window.innerheight; var ctx = canvas.getcontext('2d'), mouse = { x: 0, y: 0 }; ctx.fillstyle = "#fff"; window.addeventlistener('resize', resizecanvas, false); function resizecanvas() { canvas.width = window.innerwidth; canvas.height = window.innerheight; ctx.fillstyle = "#fff"; } canvas.addeventlistener('mousemove', function (e) { ctx.clearrect(0, 0, canvas.width, canvas.height); mouse.x = e.x - this.offsetleft; mouse.y = e.y - this.offsettop; var x = math.floor(mouse.x / canvas.offsetwidth * 100); var y = math.floor(mouse.y / canvas.offsetheight * 100); ctx.filltext("mouse : " + x + "% | " + y + "%", 50, 50); });
Comments
Post a Comment