如何在javascript中获取鼠标绘制的矩形的宽度和高度

时间:2016-07-29 01:54:31

标签: javascript

我想知道当我在HTML5画布上使用鼠标点击绘制一个矩形并拖动我如何获得每次绘制时宽度和高度的反馈。

2 个答案:

答案 0 :(得分:0)

尝试修改以下代码获取x和y坐标并计算宽度和高度。

https://jsfiddle.net/w3tian/Lbz3ayyd/

<body>

<h2 onclick="showCoords(event)">
=============================<br>
potential area that contains the rectangle
=============================<br>
</h2>

<p><strong>Hint:</strong> Try to click different places in the heading.
</p>

<p id="demo"></p>

<script>
function showCoords(event) {
   var x = event.clientX;
   var y = event.clientY;
   var coords = "X coords: " + x + ", Y coords: " + y;
   document.getElementById("demo").innerHTML = coords;
}
</script>
</body>

答案 1 :(得分:0)

我想是这样的:用鼠标坐标

计算矩形的起始位置和大小
var width = endX - startX;
var height = endY - startY;

请尝试此演示:

var Paper = can.Control(
    {
        defaults: {
            rect: {
                minWidth: 10,
                minHeight: 10
            }
        }
    },
    {
        /**
         * Initialize
         */
        init: function() {

            // Bind event handlers
            this.element.on('mousedown.paper', $.proxy(this.startDrawRect, this));
        },

        /**
         * Start drawing a rectangle
         *
         * @param   e
         */
        startDrawRect: function(e) {

            // Get canvas offset
            var offset = this.element.offset();
            this.canvasOffsetLeft = offset.left;
            this.canvasOffsetTop = offset.top;

            // Save start positions
            this.drawStartX = e.pageX - this.canvasOffsetLeft;
            this.drawStartY = e.pageY - this.canvasOffsetTop;

            // Create the rectangle
            this.drawingRect = this.createRect(this.drawStartX, this.drawStartY, 0, 0);

            // Bind event handlers
            this.element.on('mousemove.paper', $.proxy(this.drawRect, this));
            this.element.on('mouseup.paper', $.proxy(this.endDrawRect, this));
        },

        /**
         * Draw the rectangle
         *
         * @param   e
         */
        drawRect: function(e) {

            var currentX = e.pageX - this.canvasOffsetLeft;
            var currentY = e.pageY - this.canvasOffsetTop;

            // Calculate the position and size of the rectangle we are drawing
            var position = this.calculateRectPos(this.drawStartX, this.drawStartY, currentX, currentY);

            // Set position and size
            this.drawingRect.css(position);
        },

        /**
         * Finish drawing the rectangle
         *
         * @param   e
         */
        endDrawRect: function(e) {

            var currentX = e.pageX - this.canvasOffsetLeft;
            var currentY = e.pageY - this.canvasOffsetTop;

            // Calculate the position and size of the rectangle we are drawing
            var position = this.calculateRectPos(this.drawStartX, this.drawStartY, currentX, currentY);
console.log("Width :" + position.width);
console.log("Height :" + position.height);
            if (position.width < this.options.rect.minWidth || position.height < this.options.rect.minHeight) {

                // The drawn rectangle is too small, remove it
                this.drawingRect.remove();
            }
            else {

                // Set position and size
                this.drawingRect.css(position);

                // The rectangle is big enough, select it
                this.selectRect(this.drawingRect);
            }

            // Unbind event handlers
            this.element.off('mousemove.paper');
            this.element.off('mouseup.paper');
        },

        /**
         * Create a rectangle
         *
         * @param   x
         * @param   y
         * @param   w
         * @param   h
         */
        createRect: function(x, y, w, h) {

            return $('<div/>').addClass('rect').css({
                left: x,
                top: y,
                width: w,
                height: h
            }).appendTo(this.element);
        },

        /**
         * Select the given rectangle
         *
         * @param   rect
         */
        selectRect: function(rect) {

            // Deselect the previous selected rectangle
            this.selectedRect && this.selectedRect.removeClass('selected');

            // Select the given rectangle
            this.selectedRect = rect;
            this.selectedRect.addClass('selected');
        },

        /**
         * Calculate the start position and size of the rectangle by the mouse coordinates
         *
         * @param   startX
         * @param   startY
         * @param   endX
         * @param   endY
         * @returns {*}
         */
        calculateRectPos: function(startX, startY, endX, endY) {

            var width = endX - startX;
            var height = endY - startY;
            var posX = startX;
            var posY = startY;

            if (width < 0) {
                width = Math.abs(width);
                posX -= width;
            }

            if (height < 0) {
                height = Math.abs(height);
                posY -= height;
            }

            return {
                left: posX,
                top: posY,
                width: width,
                height: height
            };
        }
    }
);

$(function() {
    var paper = new Paper('#canvas', {});
});
#canvas {
  width: 600px;
  height: 400px;
  border: 1px solid #ccc;
  position: relative;
}

.rect {
  position: absolute;
  border: 2px solid rgba(199, 25, 9, 0.64);
}
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="//canjs.com/release/1.1.7/can.jquery.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <div id="canvas"></div>
</body>
</html>