Code for moving objects using JavaScript

Source: Internet
Author: User
One of the main objectives of interactive animation is to create a smooth user experience, most of which are achieved through the mouse and touch screen. In this blog post, I would like to share some common JS usage for object movement, including drag and drop effects and throwing effects. One of the main objectives of interactive animation is to create a smooth user experience, most of which are achieved through the mouse and touch screen.

In this blog post, I would like to share some common JS usage for object movement, including drag and drop effects and throwing effects.

I. Use mouse events

You can break down a single mouse-click event into two events: the mouse-press event and the button-press event. Normally, both events occur simultaneously. However, sometimes, after the mouse is pressed, the mouse will be moved for a period of time before it is displayed. This operation is called dragging, that is, pressing, moving, and releasing.

In canvas animation, mouse events can only be captured by the canvas element on the html dom tree. Therefore, we need to manually calculate the location where the mouse event occurs on the canvas, determine whether the canvas object is drawn to the canvas. The following mouse events need to be noticed: mousedown, mousemove, and mouseup. For details, refer to my related blog "JavaScript animation details (1)-loop and event listening".

2. Use touch events

With the popularity of touch screen devices, we are likely to need to capture users' touch events in animations. Although the touch screen and the mouse are different devices, fortunately, capturing touch events on the DOM tree is not much different from capturing mouse events.

The Touch events corresponding to mouse events mousedown, mousemove, and mouseup are touchstart, touchend, and touchmove respectively.

A big difference between a finger and a mouse is that the mouse always appears on the screen, but the finger is not always in the touch state. A common practice is to introduce the custom attribute isPressed to tell us whether there are fingers on the screen. For details, refer to my related blog "JavaScript animation details (1)-loop and event listening".

3. Drag events

The drag event contains three sub-events: Mouse clicking, moving, and releasing. You can drag an object on the canvas element by constantly updating the coordinates of the object so that it follows the mouse pointer. In addition, you also need a custom attribute isPressed to indicate whether the current mouse is pressed. The default value is false, indicating that the mouse is in the pop-up state. The implementation code includes the following process:

1. Capture the mousedown event and determine whether the current mouse is inside the object. When you press the mouse inside the object, set isPressed = true;

2. Capture the mousemove event. When isPressed is set to true in the handler, the system constantly updates the coordinates of the object so that it can follow the cursor position to simulate the mouse drag effect;

3. Capture the mouseup event and set isPressed to false;

The HTML code is as follows:

 

The JavaScript code is as follows:

// Create the function Ball () {this. x = 0; this. y = 0; this. radius = 20; this. fillStyle = "# f85455"; this. draw = function (cxt) {cxt. fillStyle = this. fillStyle; cxt. beginPath (); cxt. arc (this. x, this. y, this. radius, 0, 2 * Math. PI, true); cxt. closePath (); cxt. fill () ;}// obtain the current mouse position function getMouse (ev) {var mouse = {x: 0, y: 0}; var event = ev | window. event; if (event. pageX | event. pageY) {x = event. x; y = event. y;} else {var scrollLeft = document.doc umentElement. scrollLeft | document. body. scrollLeft; var scrollTop = document.doc umentElement. scrollTop | document. body. scrollTop; x = event. clientX + scrollLeft; y = event. clientY + scrollTop;} mouse. x = x; mouse. y = y; return mouse;} var canvas = document. getElementById ("canvas"), context = canvas. getContext ("2d"), ball = new Ball (), mouse = {x: 0, y: 0}, isPressed = false; ball. x = 20; ball. y = 20; // render the ball. draw (context); // the canvas of the drag event. addEventListener ("mousedown", mouseDown, false); canvas. addEventListener ("mousemove", mouseMove, false); canvas. addEventListener ("mouseup", mouseUp, false); function mouseDown (ev) {// determines whether the current mouse is in the ball mouse = getMouse (ev); if (Math. pow (mouse. x-ball. x, 2) + Math. pow (mouse. y-ball. y, 2) <= Math. pow (ball. radius, 2) {isPressed = true ;}} function mouseMove (ev) {if (isPressed) {mouse = getMouse (ev); ball. x = mouse. x; ball. y = mouse. y; context. clearRect (0, 0, canvas. width, canvas. height); ball. draw (context) ;}} function mouseUp (ev) {// indicates the mouse event isPressed = false ;}

However, this example has a bug! You will soon find that the center of the ball is on the mouse during drag and drop, especially when the mouse clicks the edge of the ball, the center of the ball suddenly jumps to the cursor position. Obviously, this is a bit abrupt.

We can make some improvements:

When the mouse is pressed, the offset between the current mouse position and the center point of the ball is recorded;

// Record the offset dx = mouse. x-ball. x; dy = mouse. y-ball. y when the mouse is pressed;

When you move the mouse, use the current position of the mouse to subtract the offset recorded when the mouse is pressed.

ball.x = mouse.x - dx;ball.y = mouse.y - dy;

4. Throwing Events

How can we throw an animation? Select an object with the mouse and drag it to move in a certain direction. After the mouse is released, the object continues to move in the drag direction.

When throwing an object, you must calculate the velocity vector of the object while dragging the object, and assign the velocity vector to the object when releasing the object. In fact, the process of calculating the velocity vector of an object during dragging is exactly the opposite of the process of applying the velocity vector to an object. When applying a velocity vector to an object, append the velocity to the original position of the object to calculate the new position of the object. This formula can be written as follows:Old location + velocity vector = new location, That isVelocity vector = new location-old location.

In order to achieve the throwing behavior, we need to make some changes to the previous code. First, check whether the mouse is pressed. If you press the mouse, use the oldX and oldY variables to save the old x and y coordinates of the ball, and update the drag speed of the ball.

The specific JavaScript code is implemented as follows:

// Create the function Ball () {this. x = 0; this. y = 0; this. radius = 20; this. fillStyle = "# f85455"; this. draw = function (cxt) {cxt. fillStyle = this. fillStyle; cxt. beginPath (); cxt. arc (this. x, this. y, this. radius, 0, 2 * Math. PI, true); cxt. closePath (); cxt. fill () ;}// obtain the current mouse position function getMouse (ev) {var mouse = {x: 0, y: 0}; var event = ev | window. event; if (event. pageX | event. pageY) {x = event. x; y = event. y;} else {var scrollLeft = document.doc umentElement. scrollLeft | document. body. scrollLeft; var scrollTop = document.doc umentElement. scrollTop | document. body. scrollTop; x = event. clientX + scrollLeft; y = event. clientY + scrollTop;} mouse. x = x; mouse. y = y; return mouse;} var canvas = document. getElementById ("canvas"), context = canvas. getContext ("2d"), ball = new Ball (), mouse = {x: 0, y: 0}, isPressed = false, oldX = 0, oldY = 0, currentX = 0, currentY = 0, vx = 0, vy = 0; ball. x = 200; ball. y = 200; // specify the distance between the mouse and the center of the ball var dx = 0, dy = 0; // render the ball. draw (context); // the canvas of the drag event. addEventListener ("mousedown", mouseDown, false); canvas. addEventListener ("mousemove", mouseMove, false); canvas. addEventListener ("mouseup", mouseUp, false); function mouseDown (ev) {// determines whether the current mouse is in the ball mouse = getMouse (ev); if (Math. pow (mouse. x-ball. x, 2) + Math. pow (mouse. y-ball. y, 2) <= Math. pow (ball. radius, 2) {isPressed = true; // record the distance between the mouse and the circle center dx = mouse when the mouse is pressed. x-ball. x; dy = mouse. y-ball. y; // get the cursor before dragging the ball. mouse = getMouse (ev); oldX = mouse. x; oldY = mouse. y ;}} function mouseMove (ev) {if (isPressed) {mouse = getMouse (ev); ball. x = mouse. x-dx; ball. y = mouse. y-dy; context. clearRect (0, 0, canvas. width, canvas. height); ball. draw (context) ;}} function mouseUp (ev) {// indicates the mouse event isPressed = false; // restores the distance between the mouse and the center of the circle to the initial value dx = 0; dy = 0; // get the mouse = getMouse (ev) after the ball is dragged; currentX = mouse. x; currentY = mouse. y; // update the velocity vector: velocity vector = new location-old location vx = (currentX-oldX) * 0.05; vy = (currentY-oldY) * 0.05; drawFrame ();} // animation function drawFrame () {animRequest = window. requestAnimationFrame (drawFrame, canvas); context. clearRect (0, 0, canvas. width, canvas. height); if (ball. x> = canvas. width-30 | ball. x <= 30 | ball. y> = canvas. height-30 | ball. y <= 30) {window. cancelAnimationFrame (animRequest);} ball. x + = vx; ball. y + = vy; ball. draw (context );}

There are still some bugs in the boundary judgment of this Demo, which will be fixed in a few days.

V. Summary

Object movement events can have many forms of total motion, but they can be divided into three separate events for control: Press, move, release, the mouse events correspond to mousedown, mousemove, and mouseup respectively, and the touch events correspond to touchstart, touchmove, and touchend respectively. By constantly updating the coordinates of an object so that it follows the pointer, you can drag and drop the canvas Element.

The above describes how to implement mobile object code using JavaScript. For more information, see other related articles in the first PHP community!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.