【问题标题】:animate 2 points of a shape to follow the mouse on mouse hover在鼠标悬停时为形状的 2 个点设置动画以跟随鼠标
【发布时间】:2015-03-04 16:57:37
【问题描述】:

我有一个简单的矢量形状,我想只为形状的 2 个顶点设置动画,以水平跟随鼠标悬停时的移动。 我想用 html5 画布把它贴在我的网站上。 有人可以帮助我了解如何做到这一点(可能很容易)吗? 谢谢!

尼克

【问题讨论】:

    标签: canvas html5-canvas raphael


    【解决方案1】:

    这是一个简单的过程:

    1. 在画布上监听mousemove 事件。

    2. 清除画布并重新绘制与鼠标位置 x 对齐的图像。

    下面是一个例子,让你在画布元素上水平拖动皮卡丘的左耳:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    var $canvas=$("#canvas");
    var canvasOffset=$canvas.offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    
    var imgLeft=3;
    var imgTop=100;
    
    var img=new Image();
    img.onload=start;
    img.src="https://dl.dropboxusercontent.com/u/139992952/multple/pikachu.png";
    function start(){
      draw(0);
      $("#canvas").mousemove(function(e){handleMouseMove(e);});
    }
    
    function draw(x){
      ctx.clearRect(0,0,cw,ch);
      ctx.drawImage(img,x-imgLeft,imgTop);
    }
    
    function handleMouseMove(e){
      // tell the browser we're handling this event
      e.preventDefault();
      e.stopPropagation();
    
      var mouseX=parseInt(e.clientX-offsetX);
    
      draw(mouseX);
    }
    body{ background-color: ivory; }
    #canvas{border:1px solid red;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <h4>Move the mouse to move Pikachu by the ear</h4>
    <canvas id="canvas" width=300 height=300></canvas>

    【讨论】:

      最近更新 更多