为形状的 2 个点设置动画以在鼠标悬停时跟随鼠标

animate 2 points of a shape to follow the mouse on mouse hover

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

尼克

这是一个简单的过程:

  1. 在您的 canvas 上监听 mousemove 事件。

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

下面是一个示例,让您通过左耳在 canvas 元素上水平拖动皮卡丘:

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>