JS Canvas单独绘制网格元素的动画 [英] JS Canvas animate grid elements individually

查看:752
本文介绍了JS Canvas单独绘制网格元素的动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用for循环生成一个六边形网格,我遇到了一些问题。

  for i = 0; i <= rows; i ++){
for(var j = 0; j <= cols; j ++){
ctx.save
ctx.translate(0 + i * distX,0 + j * distY);
drawHexagon(ctx);
ctx.fill();
ctx.restore();
}
}

我的最终目标是创建一个六边形网格当它在页面上移动时,远离鼠标光标,具有影响的区域。我不能解决如何绘制每个六边形之间的路径,我也有一个问题,试图动画的六边形。



我仍然一个画布新手,我经历了Mozilla的开发人员网络上的教程,所有的动画都是在单个对象,而不是在网格中生成的对象。



我在想应该尝试并存储网格并影响它以后,但我不知道我会如何去,我也不认为画布工作这样。



我发现这是我想做的,但我不明白它是如何工作的:
http://codepen.io/soulwire/pen/Ffvlo



我现在很好梳理,如果任何人都可以带我通过它, be great:)



编辑:我以后得到了一个网格,我想操纵这一点。

解决方案

您的链接适用于以下两种情况: / p>


  1. 鼠标附近的粒子被排斥


  2. 不在鼠标附近的粒子是在鼠标中心点附近的粒子, 吸引了回原位。更具体地,粒子沿着它们的当前中心点和它们的原始中心点之间的线向它们的原始中心点移动。


math工作方式如下:

  //给定鼠标中心点(mx,my)粒子的中心点(px,py)

//计算x的& y's
var dx = px-mx;
var dy = py-my;

//你可以通过将
//粒子的位置增加dx& dy
px + = dx / 100;
py + = dy / 100;

//你可以通过将
//粒子的位置减少dx& dy
px- = dx / 100;
py- = dy / 100;

以下是注释代码和演示(为便于理解,省略了一些代码):



  // canvas相关的变量varar canvas = document.getElementById(canvas); var ctx = canvas.getContext(2d); var cw = canvas.width; var ch = canvas.height; function reOffset(){var BB = canvas.getBoundingClientRect(); offsetX = BB.left; offsetY = BB.top; } var offsetX,offsetY; reOffset(); window.onscroll = function(e){reOffset(); } window.onresize = function(e){reOffset(); } ctx.fillStyle ='skyblue'; //鼠标相关变量var PI2 = Math.PI * 2; var mouseRadius = 75; //这是鼠标的影响半径mouseRadiusSquared = mouseRadius * mouseRadius; var mouseIsDown = false; var mx,my; //定义一堆十六进制对象存储在一个arrayvar hexRadius = 5; var hexPadding = 5; var hexes = ]; for(var y = hexRadius; y  

  {background-color:ivory; padding:10px; } #canvas {border:1px solid red;}  

  ; script src =https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js>< / script>< h4>按下鼠标以退出粒子。< br />< br>释放以将粒子返回到开始点。< / h4>< canvas id =canvaswidth = 300 height = 300& p> 


I'm generating a grid of hexagons by using a for loop and I'm having some issues

    for (var i=0; i <= rows; i++) {
        for (var j=0; j <= cols; j++) {
            ctx.save();
            ctx.translate(0+i*distX, 0+j*distY);
            drawHexagon(ctx);
            ctx.fill();
            ctx.restore();
        }
    }

My end goal is to create a grid of hexagons that move away from the mouse cursor when it's moving around the page, with an area of influence. I can't work out how to draw a path between each of the hexagons and I'm also having an issue with trying to animate the hexagons.

I'm still a canvas newbie, I went through the tutorials on Mozilla's developer network and all of the animations were on singular objects, not objects generated in a grid.

I was thinking that I should try and store the grid and affect it later but I'm not sure how I would go about that, I also don't think canvas works like that.

I found this which is pretty much what I want to do but I can't understand how it works: http://codepen.io/soulwire/pen/Ffvlo

I'm fine combing through it now, if anyone could walk me through it that would be great :)

Edit: I've since gotten a grid drawn behind the dots, I'd like to manipulate this too. I still don't understand the codepen linked above, it's a little over my head.

解决方案

Your link applies 2 forces:

  1. Particles near the mouse are repelled. More specifically, if the particles centerpoint is near the mouse centerpoint, then the particle is repelled along the line between the two centerpoints.

  2. Particles not near the mouse are attracted back to their original positions. More specifically, the particles move toward their original centerpoint along the line between their current centerpoint and their original centerpoint.

The math works like this:

// Given the mouse centerpoint (mx,my) & particle's centerpoint (px,py)

// calculate the difference between x's & y's
var dx=px-mx;
var dy=py-my;

// You can repel the particle by increasing the
// particle's position by a fraction of dx & dy
px+=dx/100;
py+=dy/100;

// And you can attract the particle by decreasing the
// particle's position by a fraction of dx & dy
px-=dx/100;
py-=dy/100;

Here's annotated code and a Demo (easing removed for ease of understanding):

// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
  var BB=canvas.getBoundingClientRect();
  offsetX=BB.left;
  offsetY=BB.top;        
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }

ctx.fillStyle='skyblue';

// mouse related variables
var PI2=Math.PI*2;
var mouseRadius=75;   // this is the mouse's radius of influence
var mouseRadiusSquared=mouseRadius*mouseRadius;
var mouseIsDown=false;
var mx,my;


// define a bunch of hex objects stored in an array
var hexRadius=5;
var hexPadding=5;
var hexes=[];
for(var y=hexRadius;y<ch;y+=hexRadius*2+hexPadding){
  for(var x=hexRadius;x<cw;x+=hexRadius*2+hexPadding){
    hexes.push({startingX:x,startingY:y,x:x,y:y});
  }}


// start a continuously running ticker loop
requestAnimationFrame(tick);


// listen for mouse events
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});


// draw every hex in its current position
function draw(){
  ctx.clearRect(0,0,cw,ch);
  ctx.beginPath();
  for(var i=0;i<hexes.length;i++){
    var h=hexes[i];
    ctx.moveTo(h.x,h.y);
    ctx.arc(h.x,h.y,hexRadius,0,PI2);
    ctx.closePath();
  }
  ctx.fill();
}

// create a continuously running ticker
function tick(time){

  // update each hex position based on its 
  // position relative to the mouse
  for(var i=0;i<hexes.length;i++){
    var h=hexes[i];
    // calculate if this hex is inside the mouse radius
    var dx=h.x-mx;
    var dy=h.y-my;
    if(mouseIsDown && dx*dx+dy*dy<mouseRadiusSquared){
      // hex is inside mouseRadius
      // so mouseDown repels hex
      h.x+=dx/120;
      h.y+=dy/120;
    }else if(h.x==h.startingX && h.y==h.startingY){
      // hex is at startingX/Y & is not being repelled
      // so do nothing
    }else{
      // hex has moved off startingX/Y
      // but is no longer being repelled
      // so gravity attracts hex back to its startingX/Y
      dx=h.x-h.startingX;
      dy=h.y-h.startingY;
      h.x-=dx/60;
      h.y-=dy/60;            
    }
  }

  // redraw the hexes in their new positions
  draw();

  // request another tick
  requestAnimationFrame(tick);
}


// listen for mousedown events
function handleMouseDown(e){

  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  // calculate the mouse position
  mx=parseInt(e.clientX-offsetX);
  my=parseInt(e.clientY-offsetY);

  // set the mousedown flag
  mouseIsDown=true;
}


// listen for mouseup events
function handleMouseUp(e){

  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  // clear the mousedown flag 
  mouseIsDown=false;
}

body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<h4>Press the mouse down to repel the particles.<br>Release to return particles to starting point.</h4>
<canvas id="canvas" width=300 height=300></canvas>

这篇关于JS Canvas单独绘制网格元素的动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆