简体   繁体   English

设置缩放时画布 x, y 位置 (JS) 的问题

[英]Problem on Canvas x, y position (JS) when setting Zoom

I'm working on canvas drawing by mouse event.我正在通过鼠标事件绘制画布。

I wanted to set body tag zoom size around 80% by using我想通过使用将 body 标签缩放大小设置为 80% 左右

document.body.style.zoom = '80%';

But when I used this code:但是当我使用这段代码时:

The positions of X, Y are wrong. X、Y 的位置错误。

Here's the code.这是代码。

function canvasX(clientX) {

    var bound = canvas.getBoundingClientRect();

    return (clientX - bound.left) * (canvas.width / bound.width);

}


function canvasY(clientY) {

    var bound = canvas.getBoundingClientRect();

    return (clientY - bound.top) * (canvas.height / bound.height);

}

tried to give layerX, layerY as a parameter but worked bad.试图将 layerX, layerY 作为参数,但效果不佳。

Positions are setted more left(-) and top(-).位置设置得更靠左(-)和顶部(-)。

It would be great if you help me out to apply zoom size on mouse position.如果您能帮我在鼠标位置上应用缩放大小,那就太好了。

This is one way这是一种方式

 const canvas = document.querySelector('#container canvas'); const ctx = canvas.getContext('2d'); let count = 0; canvas.addEventListener('mousemove', (e) => { const pos = getElementRelativeMousePosition(e, canvas); ctx.fillStyle = hsl((count++ % 10) / 10, 1, 0.5); ctx.fillRect(pos.x - 1, pos.y - 1, 3, 3); }); [...document.querySelectorAll('button')].forEach((elem) => { elem.addEventListener('click', (e) => { document.body.style.zoom = `${elem.textContent}`; }); }); function getElementRelativeMousePosition(e, elem) { const rect = elem.getBoundingClientRect(); const css = getComputedStyle(document.body); return { x: e.clientX / css.zoom - rect.left, y: e.clientY / css.zoom - rect.top, }; } function hsl(h, s, l) { return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`; }
 canvas { display: block; } #container { margin: 20px; border: 1px solid black; display: inline-block; }
 <div> <button type="button">50%</button> <button type="button">75%</button> <button type="button">100%</button> <button type="button">125%</button> <button type="button">150%</button> </div> <div id="container"> <canvas></canvas> </div>

but note that zoom is a non-standard property and is not supported in all browsers .但请注意, zoom 是一个非标准属性,并非所有浏览器都支持 It is not supported in Firefox at all. Firefox 根本不支持它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM