Измени эту функцию, чтобы приближение стало более удобным: function zoom(e) { let…
- User
Измени эту функцию, чтобы приближение стало более удобным: function zoom(e) { let scaleFactor = e.deltaY > 0 ? 0.9 : 1.1; let zoomdir = e.deltaY > 0 ? 0.2 : -0.2;
canvasScale *= scaleFactor; canvasX += (e.clientX - rect.x - rect.width * 0.5) * zoomdir; canvasY += (e.clientY - rect.y - rect.height * 0.5) * zoomdir; canvasClear(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.translate(canvasX, canvasY); ctx.scale(canvasScale, canvasScale); canvasDraw(); } - Assistant
Чтобы сделать приближение более удобным, обычно стоит применять масштабирование вокруг точки курсора мыши, а не относительно центра холста. Сейчас у вас смещение считается относительно центра, что может создавать неудобства.
Ниже версия функции
zoom(e)с улучшенным поведением приближения по всему холсту ровно вокруг курсора мыши, с более плавным масштабированием и ограничениям по минимальному/максимальному масштабу:function zoom(e) { e.preventDefault(); const scaleFactor = 1.1; const mouseX = e.clientX - rect.x; const mouseY = e.clientY - rect.y; // Текущие координаты мыши в системе канваса const dx = (mouseX - canvasX) / canvasScale; const dy = (mouseY - canvasY) / canvasScale; // Выбор направления масштабирования let newScale; if (e.deltaY < 0) { newScale = canvasScale * scaleFactor; } else { newScale = canvasScale / scaleFactor; } // Ограничим масштаб, например, от 0.1 до 10 newScale = Math.min(Math.max(newScale, 0.1), 10); // Корректируем смещение, чтобы масштабирование было относительно мыши canvasX = mouseX - dx * newScale; canvasY = mouseY - dy * newScale; canvasScale = newScale; canvasClear(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.translate(canvasX, canvasY); ctx.scale(canvasScale, canvasScale); canvasDraw(); } - User
is this: if (((x-(i.x+halfPointSize))**2 + (y-(i.y+halfPointSize))2) < halfPointSize2) { return id; } faster than this? : if (Math.sqrt((x-(i.x+halfPointSize))**2 + (y-(i.y+halfPointSize))**2) < halfPointSize) { return id; }
- Assistant
Yes, the first version without
Math.sqrtis generally faster than the second.Why?
- The second version calculates the Euclidean distance between two points using the square root:
Math.sqrt(dx*dx + dy*dy) - The first version compares the squared distance to the squared radius:
(dx*dx + dy*dy) < radius*radius
The square root operation is relatively expensive in terms of CPU cycles. By avoiding it and comparing squared values instead, you save the cost of the
Math.sqrtcall.This is a very common optimization pattern in graphics, games, and geometry when you only need to compare distances rather than get the exact distance.
So the recommended form for better performance is:
if (((x-(i.x+halfPointSize))**2 + (y-(i.y+halfPointSize))**2) < halfPointSize**2) { return id; } - The second version calculates the Euclidean distance between two points using the square root: