How can I restrict a line in a circle boundary?
I want my drawed line to be cut off when it exceeds the max length (100px) but the line keeps restricting inside a rectangle.
I think I'm missing something obvious but I can't figure it out.
var midX = canvas.width/2,
midY = canvas.height/2,
x = (mouseCurrent.x - midX),
y = (mouseCurrent.y - midY),
maxX = midX+clamp(x,-MAX_LENGTH,MAX_LENGTH),
maxY = midY+clamp(y,-MAX_LENGTH,MAX_LENGTH);
ctx.moveTo(midX, midY);
ctx.lineTo(maxX, maxY);
I've created a fiddle to show my problem:
fiddle
Your clamp function, when you pass it -MAX_LENGTH and MAX_LENGTH as the min and max boundaries, doesn't take into account anything related to the angle the line is at.
For example, in your picture, the y value would be clamped to -MAX_LENGTH, which obviously, from the middle, will extend to the bottom-most point of the circle, and the x value will be clamped to MAX_LENGTH, extending as far as the right-most point of the circle.
What you should do is calculate the angle made from the mouse position, and use the sine and cosine of that angle to determine the coordinates.
You'll want something like this:
var x = (mouseCurrent.x - midX),
y = (mouseCurrent.y - midY);
var angleInRadians = Math.atan2(x - midX, y - midY);
var realX = Math.cos(angleInRadians);
var realY = Math.sin(angleInRadians);
Then, from the realX and realY values, you should be able to create your line. You might have to tweak this a little bit. I tried to adjust based on the fact that the origin isn't at (0, 0).
Here's one way:
Get the angle from the mouse to the circle centerpoint.
Use trigonometry to get the point at radius distance at the calculated angle.
draw a line from the centerpoint to the calculated point on the circumference.
Example code and a Demo: http://jsfiddle.net/m1erickson/Zje8Y/
<!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;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var isDown=false;
var startX;
var startY;
draw(100,100);
function draw(x,y){
var cx=150;
var cy=150;
var r=50;
var dx=x-cx;
var dy=y-cy;
var angle=Math.atan2(dy,dx);
var xx=cx+r*Math.cos(angle);
var yy=cy+r*Math.sin(angle);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(cx,cy,r,0,Math.PI*2);
ctx.closePath();
ctx.stroke()
ctx.beginPath();
ctx.arc(x,y,5,0,Math.PI*2);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(cx,cy);
ctx.lineTo(xx,yy);
ctx.stroke();
ctx.beginPath();
ctx.arc(xx,yy,5,0,Math.PI*2);
ctx.closePath();
ctx.fill();
}
function handleMouseMove(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
draw(mouseX,mouseY);
}
$("#canvas").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
You can use basic trigonometry to calculate the angle and you can find the point intersecting with both the line and the circle.
First use tangent of the line to calculate angle. Then use angle value to find x and y coordinates of the point that you are looking for. Here is the code:
angle = Math.atan2(mouseCurrent.y - midY, mouseCurrent.x - midX);
maxY = midY + Math.sin(angle) * MAX_LENGTH;
maxX = midX + Math.cos(angle) * MAX_LENGTH;
Related
I'm trying to draw with the mouse over a HTML5 canvas, but the only way that it seems to work well is if the canvas is in the position 0,0 (upper left corner) if I change the canvas position, for some reason it doesn't draw like it should. Here is my code.
function createImageOnCanvas(imageId){
document.getElementById("imgCanvas").style.display = "block";
document.getElementById("images").style.overflowY= "hidden";
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");
var img = new Image(300,300);
img.src = document.getElementById(imageId).src;
context.drawImage(img, (0),(0));
}
function draw(e){
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");
posx = e.clientX;
posy = e.clientY;
context.fillStyle = "#000000";
context.fillRect (posx, posy, 4, 4);
}
The HTML part
<body>
<div id="images">
</div>
<canvas onmousemove="draw(event)" style="margin:0;padding:0;" id="imgCanvas"
class="canvasView" width="250" height="250"></canvas>
I have read there's a way of creating a simple function in JavaScript to get the right position, but I have no idea about how to do it.
The Simple 1:1 Scenario
For situations where the canvas element is 1:1 compared to the bitmap size, you can get the mouse positions by using this snippet:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
Just call it from your event with the event and canvas as arguments. It returns an object with x and y for the mouse positions.
As the mouse position you are getting is relative to the client window you’ll have to subtract the position of the canvas element to convert it relative to the element itself.
Example of integration in your code:
// put this outside the event loop..
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");
function draw(evt) {
var pos = getMousePos(canvas, evt);
context.fillStyle = "#000000";
context.fillRect (pos.x, pos.y, 4, 4);
}
Note: borders and padding will affect position if applied directly to the canvas element so these needs to be considered via getComputedStyle() – or apply those styles to a parent div instead.
When Element and Bitmap are of different sizes
When there is the situation of having the element at a different size than the bitmap itself, for example, the element is scaled using CSS or there is pixel-aspect ratio etc. you will have to address this.
Example:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect(), // abs. size of element
scaleX = canvas.width / rect.width, // relationship bitmap vs. element for x
scaleY = canvas.height / rect.height; // relationship bitmap vs. element for y
return {
x: (evt.clientX - rect.left) * scaleX, // scale mouse coordinates after they have
y: (evt.clientY - rect.top) * scaleY // been adjusted to be relative to element
}
}
With transformations applied to context (scale, rotation etc.)
Then there is the more complicated case where you have applied transformation to the context such as rotation, skew/shear, scale, translate etc. To deal with this you can calculate the inverse matrix of the current matrix.
Newer browsers let you read the current matrix via the currentTransform property and Firefox (current alpha) even provide an inverted matrix through the mozCurrentTransformInverted. Firefox however, via mozCurrentTransform, will return an Array and not DOMMatrix as it should. Neither Chrome, when enabled via experimental flags, will return a DOMMatrix but a SVGMatrix.
In most cases however you will have to implement a custom matrix solution of your own (such as my own solution here – free/MIT project) until this get full support.
When you eventually have obtained the matrix regardless of path you take to obtain one, you’ll need to invert it and apply it to your mouse coordinates. The coordinates are then passed to the canvas which will use its matrix to convert it to back wherever it is at the moment.
This way the point will be in the correct position relative to the mouse. Also here you need to adjust the coordinates (before applying the inverse matrix to them) to be relative to the element.
An example just showing the matrix steps:
function draw(evt) {
var pos = getMousePos(canvas, evt); // get adjusted coordinates as above
var imatrix = matrix.inverse(); // get inverted matrix somehow
pos = imatrix.applyToPoint(pos.x, pos.y); // apply to adjusted coordinate
context.fillStyle = "#000000";
context.fillRect(pos.x-1, pos.y-1, 2, 2);
}
An example of using currentTransform when implemented would be:
var pos = getMousePos(canvas, e); // get adjusted coordinates as above
var matrix = ctx.currentTransform; // W3C (future)
var imatrix = matrix.invertSelf(); // invert
// apply to point:
var x = pos.x * imatrix.a + pos.y * imatrix.c + imatrix.e;
var y = pos.x * imatrix.b + pos.y * imatrix.d + imatrix.f;
Update: I made a free solution (MIT) to embed all these steps into a single easy-to-use object that can be found here and also takes care of a few other nitty-gritty things most ignore.
You can get the mouse positions by using this snippet:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
};
}
This code takes into account both changing coordinates to canvas space (evt.clientX - rect.left) and scaling when canvas logical size differs from its style size (/ (rect.right - rect.left) * canvas.width see: Canvas width and height in HTML5).
Example: http://jsfiddle.net/sierawski/4xezb7nL/
Source:
jerryj comment on http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
You need to get the mouse position relative to the canvas
To do that you need to know the X/Y position of the canvas on the page.
This is called the canvas’s “offset”, and here’s how to get the offset. (I’m using jQuery in order to simplify cross-browser compatibility, but if you want to use raw javascript a quick Google will get that too).
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
Then in your mouse handler, you can get the mouse X/Y like this:
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
}
Here is an illustrating code and fiddle that shows how to successfully track mouse events on the canvas:
http://jsfiddle.net/m1erickson/WB7Zu/
<!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;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#downlog").html("Down: "+ mouseX + " / " + mouseY);
// Put your mousedown stuff here
}
function handleMouseUp(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#uplog").html("Up: "+ mouseX + " / " + mouseY);
// Put your mouseup stuff here
}
function handleMouseOut(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#outlog").html("Out: "+ mouseX + " / " + mouseY);
// Put your mouseOut stuff here
}
function handleMouseMove(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#movelog").html("Move: "+ mouseX + " / " + mouseY);
// Put your mousemove stuff here
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Move, press and release the mouse</p>
<p id="downlog">Down</p>
<p id="movelog">Move</p>
<p id="uplog">Up</p>
<p id="outlog">Out</p>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
The easiest way to compute the correct mouse click or mouse move position on a canvas event is to use this little equation:
canvas.addEventListener('click', event =>
{
let bound = canvas.getBoundingClientRect();
let x = event.clientX - bound.left - canvas.clientLeft;
let y = event.clientY - bound.top - canvas.clientTop;
context.fillRect(x, y, 16, 16);
});
If the canvas has padding-left or padding-top, subtract x and y via:
x -= parseFloat(style['padding-left'].replace('px'));
y -= parseFloat(style['padding-top'].replace('px'));
Refer this question: The mouseEvent.offsetX I am getting is much larger than actual canvas size
.I have given a function there which will exactly suit in your situation
I write code but it's not run.
I have 2 tag canvas. When i change properties height of canvas < 100 then arrow hidden. And if i didn't write tag div before tag canvas its run normal. Thank you for support!!!!
Source code:
<body>
<div id="yendau">LOL</div>
<canvas id="c" width="500" height="100">Brower of you doesn't not support Canvas</canvas>
<div>Yolooooooooooo</div>
<canvas id="d" width="500" height="300">Brower of you doesn't not support Canvas</canvas>
<script src="jquery-1.9.1.js"></script>
<script langauage="javascript">
function canvas_arrow(context, fromx, fromy, tox, toy){
var headlen = 20; // length of head in pixels
var dx = tox-fromx;
var dy = toy-fromy;
var angle = Math.atan2(dy,dx);
context.moveTo(fromx, fromy);
context.lineTo(tox, toy);
context.lineWidth=2;
context.moveTo(tox, toy);
context.lineTo(tox-headlen*Math.cos(angle+Math.PI/6),toy-headlen*Math.sin(angle+Math.PI/6));
context.moveTo(tox, toy);
context.lineTo(tox-headlen*Math.cos(angle-Math.PI/6),toy-headlen*Math.sin(angle-Math.PI/6));
}
$('document').ready(function(){
var count= parseInt($("canvas").length);
for(var i=0; i< count; i++){
var ctx= $("canvas")[i].getContext('2d');
ctx.beginPath();
//var x= $('#c').offset().left-15;
//var y= $('#c').offset().top-15;
var x= $('#'+$("canvas")[i].id).offset().left;
var y= $('#'+$("canvas")[i].id).offset().top+15;
var x1= x+100;
canvas_arrow(ctx,x,y,x1,y);
ctx.stroke();
}
});
You don't need to add the offset of the canvas when calculating x,y. In your case, doing that will quickly push your arrow off the canvas.
The canvas offset is useful when calculating the mouse position, but not useful when drawing on the canvas itself. That's because the mouse coordinates are always relative to the top-left of the page--not the top left of the canvas.
The top-left corner of the canvas is x=0, y=0. So just set x,y to your desired coordinates bases on:
x increases from zero as you move rightward across the canvas.
y increased from zero as you move downward across the canvas.
I am using plain vanilla html/javascript canvas (no library). I have a way to calculate angles from two points, My theory is that I take the angle and draw a line on that angle by looping the desired horizontal distance (x) and performing some calculation with the angle so it stays straight (y), I can only find stuff about complex curves and circular lines on google. In each loop do I * the angle by its self? I am not very go at visualizing numbers
var point1 = {
x: 20,
y: 20
};
var point2 = {
x: 40,
y: 40
};
// angle method 1
var radians = Math.atan2(point2.y - point1.y, pv2.x - point1.x);
// angle method2
var degrees = Math.atan2(point2.y - point1.y, point2.x - point1.x) * 180 / Math.PI;
Update: after MarkE's answer things are looking upside down but much much better...
the light straight lines are showing the angle of a wave line from two points but the angle is some how flipped... I am working at understanding this
Looks like I forgot to sin...
You can use trigonometry to calculate the x,y at a specified length along the line including point1 and point2.
var dx=point2.x-point1.x;
var dy=point2.y-point1.y;
var radianAngle=Math.atan2(dy,dx);
var desiredLength=150;
var x=point1.x+desiredLength*Math.cos(radianAngle);
var y=point1.y+desiredLength*Math.sin(radianAngle);
Example code and a Demo: http://jsfiddle.net/m1erickson/sztC8/
<!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;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.strokeStyle="red";
var point1 = {
x: 20,
y: 20
};
var point2 = {
x: 40,
y: 40
};
var PI2=Math.PI*2;
var dx=point2.x-point1.x;
var dy=point2.y-point1.y;
var radianAngle=Math.atan2(dy,dx);
var desiredLength=150;
var x=point1.x+desiredLength*Math.cos(radianAngle);
var y=point1.y+desiredLength*Math.sin(radianAngle);
ctx.beginPath();
ctx.arc(point1.x,point1.y,5,0,PI2);
ctx.closePath();
ctx.arc(point2.x,point2.y,5,0,PI2);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(point1.x,point1.y);
ctx.lineTo(x,y);
ctx.stroke();
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
hey guys i am taking an angle input from user and using it to stroke the line in that
direction
function makeline(angle)
{
context.clearRect(0, 0, theCanvas.width, theCanvas.height);
angle=document.getElementById("radi").value;
//alert(angle);
angle=(Math.PI/180)*angle;
//getting end coordinates
x2= 0+theCanvas.width*Math.cos(angle) //here angle should be in radians
y2=400+theCanvas.width *Math.sin(angle);
context.beginPath();
context.setLineDash([3,2]);
context.lineWidth=10;
context.strokeStyle="black";
context.moveTo(400,400);
context.lineTo(x2,y2);
context.stroke();
}
now is it possible to move an image on the line that is generated every time with the new angle. Please help. take the image of a car or anything.
Yes, it is. You can already work out where to draw the image using simple trigonometry. What you need to do is look into how to draw an image with arbitrary rotation onto a canvas.
Here's a quick sample of drawing a line of variable length and angle to a canvas. Add to it the results of your research into drawing rotated images and you're done.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);
function mInit()
{
byId('angleSlider').addEventListener('change', onSliderChange, false);
byId('lengthSlider').addEventListener('change', onSliderChange, false);
}
function onSliderChange(evt)
{
var slider = this;
var tgtSpan = slider.nextSibling;
tgtSpan.innerHTML = slider.value;
drawCurValues();
}
function drawCurValues()
{
var angle = byId('angleSlider').value;
var displacement = byId('lengthSlider').value;
var originX = 128, originY = 128; // center of 256x256 canvas
var can = byId('outputCanvas');
var ctx = can.getContext('2d');
ctx.clearRect(0,0,can.width, can.height);
var xOfs, yOfs;
yOfs = displacement * Math.sin( angle * 3.141/180 );
xOfs = displacement * Math.cos( angle * 3.141/180 );
yOfs *= -1; // since canvas 0,0 is at top-left, rather than bottom-left. 90 deg should be above origin, not below it
ctx.beginPath();
ctx.moveTo(originX,originY);
ctx.lineTo( originX+xOfs, originY+yOfs );
ctx.closePath();
ctx.stroke();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
</script>
<style>
canvas
{
border: solid 1px black;
}
</style>
</head>
<body>
Angle <input type='range' value='0' min='0' max='360' id='angleSlider'/><span id='angleDisplay'></span><br>
Length <input type='range' value='0' min='0' max='181' id='lengthSlider'/><span id='lengthDisplay'></span><br> <!-- 181 = sqrt(2) * 128; i.e dist from center to corners of canvas -->
<canvas width='256' height='256' id='outputCanvas'></canvas>
</body>
</html>
I have drawn a polygon with the following code. Now I want to resize that polygon animatedly. In detail, I want to set an angular movement to one side of the polygon, such that it makes an arc, and so changes the size of polygon. I googled for everything regarding the polygon animation, but didn't get anything, though there is plenty of material for line animation.
<script>
$(function(){
var c=$('#myCanvas');
var ctx=c.getContext("2d");
ctx.fillStyle='#f00';
ctx.beginPath();
ctx.moveTo(0,40);
ctx.lineTo(80,200);
ctx.lineTo(100,200);
ctx.lineTo(40,0);
ctx.closePath();
ctx.fill();
</script>
</div>
Is it possible to pick a line of a polygon and animate it, to change the shape of the polygon?
The trick is to store the coordinates of the polygon in an array and work on the numbers in that array instead.
Then render what you have in the array to canvas. Worry-free when it comes to translation and what-have-you.
See canvas as only a snapshot of whatever you have in the array at the moment.
Ok this is what I did and which has worked out:
<script>
var canvas = document.getElementById("myCanvas");
var dc = canvas.getContext("2d");
var angle = 0;
var x = canvas.width;
var y = canvas.height;
window.setInterval(function(){
angle = (angle + 1) % 360;
dc.clearRect(0, 0, canvas.width, canvas.height);
dc.save();
dc.fillStyle = "#DDDDDD";
dc.translate(x/2,y);
dc.rotate( angle*Math.PI/270 ); // rotate 90 degrees
dc.translate(0,0);
dc.beginPath();
dc.moveTo(-x/16, 0);
dc.lineTo(-x, y/2);
dc.lineTo(-x/2,y);
dc.lineTo(-0,y/16);
dc.closePath();
dc.fill();
dc.restore();
}, 20);
</script>
I referred to Bill's answer at https://stackoverflow.com/a/2767556/2163837 Thanks for your help also.
Here’s how to turn a triangle into a square, a square into a pentagon, etc ….
This code draws a regular polygon with the specified number of sides:
function drawPolygon(sideCount,size,centerX,centerY){
// draw a regular polygon with sideCount sides
ctx.save();
ctx.beginPath();
ctx.moveTo (centerX + size * Math.cos(0), centerY + size * Math.sin(0));
for (var i = 1; i <= sideCount;i += 1) {
var x=centerX + size * Math.cos(i * 2 * Math.PI / sideCount);
var y=centerY + size * Math.sin(i * 2 * Math.PI / sideCount);
ctx.lineTo (x, y);
}
ctx.stroke();
ctx.fill();
ctx.restore();
}
Animating odd-sided polygons into even-sided polygons
In this illustration, you can animate a triangle into a square by animating each colored vertex on the triangle to its corresponding position on the square. All odd-sided polygons are transformed into even-sided polygons that same way.
Animating even-sided polygons into odd-sided polygons
In this illustration, you can animate a square into a pentagon by animating each colored vertex on the square to its corresponding position on the pentagon. In this case, you have to also cut the left-most yellow vertex in two and animate the two portions to the two yellow vertices on the pentagon. All even-sided polygons are transformed into odd-sided polygons that same way.
Here’s code and a Fiddle: http://jsfiddle.net/m1erickson/DjV5f/
<!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; padding:10px; }
canvas{border:1px solid red;}
p{font-size:24px;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
//
var colors=["","blue","green","black"];
drawPolygon(3,50,70,70,2,"blue","red",colors,true);
colors=["","blue","yellow","green","black"];
drawPolygon(4,50,215,70,2,"blue","red",colors,false);
//
ctx.beginPath();
ctx.moveTo(0,162);
ctx.lineTo(300,162);
ctx.stroke();
//
var colors=["black","blue","yellow","green"];
drawPolygon(4,50,70,250,2,"blue","red",colors,true);
colors=["black","blue","yellow","yellow","green"];
drawPolygon(5,50,215,250,2,"blue","red",colors,false);
function drawPolygon(sideCount,size,centerX,centerY,strokeWidth,strokeColor,fillColor,colorPts,showBursePoint){
// draw a regular polygon with sideCount sides
ctx.save();
ctx.beginPath();
ctx.moveTo (centerX + size * Math.cos(0), centerY + size * Math.sin(0));
for (var i = 1; i <= sideCount;i += 1) {
var x=centerX + size * Math.cos(i * 2 * Math.PI / sideCount);
var y=centerY + size * Math.sin(i * 2 * Math.PI / sideCount);
ctx.lineTo (x, y);
}
ctx.fillStyle=fillColor;
ctx.strokeStyle = strokeColor;
ctx.lineWidth = strokeWidth;
ctx.stroke();
ctx.fill();
ctx.restore();
// draw vertex points
for (var i = 1; i <= sideCount;i += 1) {
var x=centerX + size * Math.cos(i * 2 * Math.PI / sideCount);
var y=centerY + size * Math.sin(i * 2 * Math.PI / sideCount);
drawPoint(x,y,colorPts[i]);
}
// draw point where this poly will "burst" to create next poly
if(showBursePoint){
var burstX= centerX + size * Math.cos( Math.floor(sideCount/2) * 2 * Math.PI / sideCount);
var burstY= centerY;
drawPoint(burstX, burstY, "yellow");
}
}
function drawPoint(x,y,fill){
ctx.save()
ctx.strokeStyle="black";
ctx.lineWidth=2;
ctx.fillStyle=fill;
ctx.beginPath();
ctx.arc(x,y,6,0,Math.PI*2,false);
ctx.fill();
ctx.stroke();
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<p>Regular polygons (3-8 sides)</p><br/>
<p>Unmoving anchor point is green</p><br/>
<p>Burst point is yellow</p><br/>
<canvas id="canvas" width=300 height=350></canvas>
</body>
</html>