Получить ограничивающий прямоугольник клиента без границ
Я создал функцию, которая преобразует координаты мыши в пиксельные координаты холста:
/* Returns pixel coordinates according to the pixel that under the mouse cursor**/
HTMLCanvasElement.prototype.relativeCoords = function(event) {
var x,y;
//This is the current screen rectangle of canvas
var rect = this.getBoundingClientRect();
//Recalculate mouse offsets to relative offsets
x = event.clientX - rect.left;
y = event.clientY - rect.top;
//Also recalculate offsets of canvas is stretched
var width = rect.right - rect.left;
//I use this to reduce number of calculations for images that have normal size
if(this.width!=width) {
var height = rect.bottom - rect.top;
//changes coordinates by ratio
x = x*(this.width/width);
y = y*(this.height/height);
}
//Return as an array
return [x,y];
}
Вы можете увидеть демонстрацию расчет координат пикселя. Проблема заключается в том, что решения не выполняются для изображений имеющих border
набор свойств.
Как я могу вычесть ширину границы из прямоугольника? Производительность имеет значение, так как этот расчет часто выполняется во время событий перемещения мыши.
Ответы
Ответ 1
getComputedStyle
содержит требуемую информацию:
Извлеките информацию о границе один раз в начале вашего приложения после того, как была установлена граница холста.
// get a reference to the canvas element
var canvas=document.getElementById('yourCanvasId');
// get its computed style
var styling=getComputedStyle(canvas,null);
// fetch the 4 border width values
var topBorder=styling.getPropertyValue('border-top-width');
var rightBorder=styling.getPropertyValue('border-right-width');
var bottomBorder=styling.getPropertyValue('border-bottom-width');
var leftBorder=styling.getPropertyValue('border-left-width');
Если вы применяете эти переменные ширины границы для всего приложения, вы можете использовать эти предварительно выбранные переменные в свой HTMLCanvasElement.prototype.relativeCoords.
Удачи вам в вашем проекте!