Html5 canvas implements arrows that follow the mouse rotation, html5canvas
Examples of this article are as follows:
Copy XML/HTML Code to clipboard
- <! DOCTYPE html>
- <Html>
- <Head>
- <Meta charset = "UTF-8"/>
- <Meta http-equiv = "X-UA-Compatible" content = "IE = edge"/>
- <Title> canvas: arrows that rotate with the mouse </title>
- <Style>
- * {Padding: 0; margin: 0}
- </Style>
- </Head>
- <Body>
- <Canvas width = "500" height = "500" style = "border: 1px solid #555; display: block; margin: 0 auto;"> </canvas>
- <Script>
- Var arrow = function (){
- This. x = 0;
- This. y = 0;
- This. color = "# f90"
- This. rolation = 0;
- }
- Var canvas = document. querySelector ('canvas ')
- Var ctx = canvas. getContext ('2d ');
- Arrow. prototype. draw = function (ctx ){
- Ctx. save ();
- Ctx. translate (this. x, this. y );
- Ctx. rotate (this. rolation)
- Ctx. fillStyle = this. color;
- Ctx. beginPath ();
- Ctx. moveTo (0, 15 );
- Ctx. lineTo (-50, 15 );
- Ctx. lineTo (-50,-15 );
- Ctx. lineTo (0,-15 );
- Ctx. lineTo (0,-35 );
- Ctx. lineTo (50, 0 );
- Ctx. lineTo (0, 35 );
- Ctx. closePath ()
- Ctx. fill ();
- Ctx. restore ();
- }
- Var Arrow = new arrow ();
- Arrow. x = canvas. width/2;
- Arrow. y = canvas. height/2;
- Var c_x, c_y; // The position relative to the canvas coordinate;
- Var isMouseDown = false;
- Arrow. draw (ctx)
- Canvas. addEventListener ('mousedown ', function (e ){
- IsMouseDown = true;
- }, False)
- Canvas. addEventListener ('mousemove ', function (e ){
- If (isMouseDown = true ){
- C_x = getPos (e). x-canvas.offsetLeft;
- C_y = getPos (e). y-canvas.offsetTop;
- // SetInterval (FIG, 1000/60)
- RequestAnimationFrame (drawFram)
- }
- }, False)
- Canvas. addEventListener ('mouseup', function (e ){
- IsMouseDown = false;
- }, False)
- Function drawFram (){
- Var dx= c_x-Arrow.x;
- Var dy = c_y-Arrow.y;
- Arrow. rolation = Math. atan2 (dy, dx );
- Ctx. clearRect (0, 0, canvas. width, canvas. height );
- Arrow. draw (ctx)
- }
- Function getPos (e ){
- Var mouse = {x: 0, y: 0}
- Var ee = e | event;
- If (e. pageX | e. pageY ){
- Mouse. x = e. pageX;
- Mouse. y = e. pageY;
- } Else {
- Mouse.xe.e.pagex?document.body.scrollleft?document.document.doc umentElement. scrollLeft;
- Mouse.yunce.pagey?document.body.scrolltop=document.document.doc umentElement. scrollTop;
- }
- Return mouse;
- }
- </Script>
- </Body>
- </Html>
DEMO address: http://codepen.io/jonechen/pen/eZpgWd
It's not complicated to implement the DEMO directly, but the sparrows are small and dirty, mainly involving the following knowledge points:
1. Basic Drawing of canvas;
2. monitors various js events;
3. js animation;
4. trigonometric functions combined with the basic application of js in canvas;
The above is all the content of this article, hoping to help you learn.
Original article: http://www.cnblogs.com/jone-chen/p/5243439.html