Search code examples
javascriptanimationhtml5-canvastrigonometryhexagonal-tiles

Tracing the edge of a hexagon pixel by pixel


To create an animation in Javascript using an HTML5 canvas I first need to be able to describe a point by point path around a hexagonal shape. I already have the x/y coordinate of each vertex. I don't know which direction I will be travelling around the edge so any solution should be able to work in either direction.

The radius, and therefore each side, of the hexagon is 20 pixels. I need to produce a set of 20 points for each side that maps the x and y position of each pixel in that path. This is obviously easy for straight lines where each pixel increments 1 for each step and the other axis remains static. With the angled sides I am failing get the trigonometry required to plot the points.

I'm fairly positive this is trivial but would appreciate some help getting clear in my mind.


Solution

  • This code will draw equidistant dots from point x1/y1 to point x2/y2.

    Works in reverse also (x2/y2 to x1/y1).

    Since you have all the x/y for each vertex, you should be good to go!

    Here is the code and a Fiddle: http://jsfiddle.net/m1erickson/pW4De/

        <!doctype html>
        <html>
        <head>
        <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
        <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    
        <style>
            body{ background-color: ivory; }
            canvas{border:1px solid red;}
            p{font-size:24px;}
        </style>
    
        <script>
            $(function(){
    
                var canvas=document.getElementById("canvas");
                var ctx=canvas.getContext("2d");
    
                DrawDottedLine(300,400,7,7,7,20,"green");
    
                function DrawDottedLine(x1,y1,x2,y2,dotRadius,dotCount,dotColor){
                  var dx=x2-x1;
                  var dy=y2-y1;
                  var spaceX=dx/(dotCount-1);
                  var spaceY=dy/(dotCount-1);
                  var newX=x1;
                  var newY=y1;
                  for (var i=0;i<dotCount;i++){
                          drawDot(newX,newY,dotRadius,dotColor);
                          newX+=spaceX;
                          newY+=spaceY;              
                   }
                   drawDot(x1,y1,3,"red");
                   drawDot(x2,y2,3,"red");
                }
                function drawDot(x,y,dotRadius,dotColor){
                    ctx.beginPath();
                    ctx.arc(x,y, dotRadius, 0, 2 * Math.PI, false);
                    ctx.fillStyle = dotColor;
                    ctx.fill();              
                }           
    
            }); // end $(function(){});
        </script>
    
        </head>
    
        <body>
    
        <canvas id="canvas" width=307 height=407></canvas>
    
        </body>
        </html>