最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Drawing rectangles (divs) with the mouse - Stack Overflow

programmeradmin0浏览0评论

I am trying to draw rectangles (divs) using mouse events. Here is my code:

Basically I'm doing the following:

  1. On mousedown I save the mouse coordinates, create a new div with size: width=0, height=0, and bind event handlers for mousemove and mouseup.

  2. On mousemove I resize the div based on the current mouse position.

  3. On mouseup I unbind the event handlers for mousemove and mouseup.

It seems to work good in Firefox, and even IE 10, but in Chrome sometimes the mousemove event fires only 2 or 3 times, after mousedown, so the drawn div doesn't get resized.

I can't find the reason why. Any help is appreciated.

I am trying to draw rectangles (divs) using mouse events. Here is my code:

http://jsbin./apediti/2/edit

Basically I'm doing the following:

  1. On mousedown I save the mouse coordinates, create a new div with size: width=0, height=0, and bind event handlers for mousemove and mouseup.

  2. On mousemove I resize the div based on the current mouse position.

  3. On mouseup I unbind the event handlers for mousemove and mouseup.

It seems to work good in Firefox, and even IE 10, but in Chrome sometimes the mousemove event fires only 2 or 3 times, after mousedown, so the drawn div doesn't get resized.

I can't find the reason why. Any help is appreciated.

Share Improve this question edited Oct 8, 2013 at 22:18 Tamás Pap asked Oct 8, 2013 at 22:08 Tamás PapTamás Pap 18.3k15 gold badges73 silver badges104 bronze badges 2
  • Works for me in latest Chrome - do you see any errors in the console? – tckmn Commented Oct 8, 2013 at 22:10
  • No errors in the console, and the 'bug' only appears sometimes. Try this for example: draw a rectangle, and when you draw a second one make sure to release the mouse when you are over the first div. Now try to create a 3th rectangle. The bug should appear. Does it? (Thanks) – Tamás Pap Commented Oct 8, 2013 at 22:14
Add a ment  | 

1 Answer 1

Reset to default 3

This is happening because Chrome is attempting to select the hovered-over rect element on drag. To fix this, simply prevent the rect element from being selected by setting the user-select CSS property to none (this is vendor prefixed and will not work on IE9 or lower):

.rect {
    position: absolute;
    border: 2px solid rgba(199, 25, 9, 0.64);
    -webkit-user-select: none;  /* Chrome, Safari, Opera */
    -moz-user-select: none; /* Firefox all */
    -ms-user-select: none; /* IE 10+ */
    user-select: none;  
}

Modified JSBin.

发布评论

评论列表(0)

  1. 暂无评论