问题描述
我有一个画布字段。我需要做三件事:缩放,移动和指向像素。 我轻松制作了第一个,但是第二个引起了一些问题。 我是以这种方式进行的(我想在所需像素的中心位置放置一个正方形):
let size = Math.round(3.5 * Math.pow(3 / Math.log10(scale + 1),2 / 3));
chosenPixelShower.style.width = size;
chosenPixelShower.style.height = size;
chosenPixelShower.style.left = canvas.offsetLeft - scale * canvas.offsetWidth / 2 + 2 * chosenPixel.x * scale - size / 2;
chosenPixelShower.style.top = canvas.offsetTop - scale * canvas.offsetHeight / 2 + 2 * chosenPixel.y * scale - size / 2;
chosenPixelShower
只是我需要放置的position:absolute
的div。
我从onclick
事件中获得了selectedPixel:
canvas.onclick = choosePixel;
function choosePixel(e)
{
chosenPixel = {"x": Math.floor(e.offsetX / 2),"y": Math.floor(e.offsetY / 2)};
}
它在scale = 1
上很好用,但是如果我以此方式更改canvas
的比例,它会开始指向更高一点并向左一点。看起来offsetHeight,offsetLeft等给出的值不是正确的:
canvas.style.transform = `translate(-50%,-50%) scale(${scale})`;
P.S。 HTML结构是这样的:
<div id='main'>
<canvas id="canvas" width='3180px' height='800px'></canvas>
<div id='chosenPixelShower'></div>
</div>
其中#main绝对位于左侧0,顶部0,高度100%和宽度80%
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)