How to move canvas speedometer needle slowly? - html

I use following codes in order to move a picture in canvas for my speedometer.
var meter = new Image,
needle = new Image;
window.onload = function () {
var c = document.getElementsByTagName('canvas')[0];
var ctx = c.getContext('2d');
setInterval(function () {
ctx.save();
ctx.clearRect(0, 0, c.width, c.height);
ctx.translate(c.width / 2, c.height / 2);
ctx.drawImage(meter, -165, -160);
ctx.rotate((x * Math.PI / 180);
/ x degree
ctx.drawImage( needle, -13, -121.5 );
ctx.restore();
},50);
};
meter.src = 'meter.png';
needle.src = 'needle.png';
}
However I want to move the needle slowly to the degree which I entered such as speedtest webpages. Any idea?
Thanks.

Something like this should work:
var meter = new Image,
needle = new Image;
window.onload = function () {
var c = document.getElementsByTagName('canvas')[0],
ctx = c.getContext('2d'),
x, // Current angle
xTarget, // Target angle.
step = 1; // Angle change step size.
setInterval(function () {
if(Math.abs(xTarget - x) < step){
x = xTarget; // If x is closer to xTarget than the step size, set x to xTarget.
}else{
x += (xTarget > x) ? step : // Increment x to approach the target.
(xTarget < x) ? -step : // (Or substract 1)
0;
}
ctx.save();
ctx.clearRect(0, 0, c.width, c.height);
ctx.translate(c.width / 2, c.height / 2);
ctx.drawImage(meter, -165, -160);
ctx.rotate((x * Math.PI / 180); // x degree
ctx.drawImage( needle, -13, -121.5 );
ctx.restore();
},50);
};
dial.src = 'meter.png';
needle.src = 'needle.png';
}
I'm using a shorthand if / else here to determine whether to add 1 to x, substract 1, or do nothing. Functionally, this is the same as:
if(xTarget > x){
x += step;
}else if(xTarget < x){
x += -step;
}else{
x += 0;
}
But it's shorter, and in my opinion, just as easy to read, once you know what a shorthand if (ternary operator) looks like.
Please keep in mind that this code assumes x is a integer value (So, not a float, just a rounded int).

Related

How to let a user remove an object in canvas 2D from an arbitrary position

I've got some simple barchart making code written which allows a user to add a barchart but I'd also like to allow them to remove a barchart of choice from the canvas. I don't think this should be overly difficult but I'm relatively new to html and I'm quite unsure how to go about it. Any help would be greatly appreciated.
Here's the code I've written.
<html>
<head>
<script>
var barVals = [];
function draw() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// calculate highest bar value (used to scale the rest)
var highest = 0;
for (var b=0; b<barVals.length; b++) {
if (barVals[b]>highest)
highest=barVals[b];
}
// we have 8 horizontal lines so calculate an appropriate scale
var lineSpacing = 1;
var highestLine = 7*lineSpacing;
while (highestLine<highest) {
lineSpacing *= 10;
highestLine = 7*lineSpacing;
}
// grey background
ctx.fillStyle = "rgb(200,200,200)";
ctx.fillRect (0, 0, 600, 450);
// draw and (if we have any data to scale from) label horizontal lines
var lineNum = 0;
ctx.fillStyle="white";
ctx.font="16px sans-serif";
for (y=0; y<=350; y+=50) {
// line
ctx.beginPath();
ctx.moveTo(50,y+50);
ctx.lineTo(550,y+50);
ctx.stroke();
// label (the 6 is an offset to centre the text vertically on the line)
if (barVals.length>0) {
ctx.fillText(lineSpacing*lineNum, 10, 400-y+6);
lineNum++;
}
}
// draw boxes (widths based on how many we have)
var barWidth = 500/barVals.length;
var halfBarWidth = barWidth/2;
for (b=0; b<barVals.length; b++) {
// calculate size of box and draw it
var x = 60+b*barWidth;
var hgt = (barVals[b]/highestLine)*350; // as fraction of highest line
if (b%2==0)
ctx.fillStyle = "red";
else
ctx.fillStyle = "blue";
ctx.fillRect(x,400-hgt,barWidth,hgt);
// calculate position of text and draw it
ctx.fillStyle="white";
var metrics = ctx.measureText(barVals[b]);
var halfTextWidth = metrics.width/2;
x = 60+halfBarWidth+(b*barWidth)-halfTextWidth;
ctx.fillText(barVals[b], x, 420-hgt);
}
}
function addBar() {
var textBoxObj = document.getElementById("barVal");
barVals.push(parseInt(textBoxObj.value)); // add new value to end of array. As an integer not a string!!
draw(); // redraw
textBoxObj.value = 0;
}
</script>
</head>
<body onload="draw();">
<center>
<canvas id="canvas" width="600" height="450"></canvas>
<form>
<BR>
<input type=button value='Add Bar' onclick='addBar();'> <input id='barVal' value=0>
</form>
</body>
</html>
Removing a specific chart isn't much different from adding. In fact you almost have everything you need right in your code yet.
Let's take a look at it. As soon as you click on the "Add Bar" button it will add a value from the associated textbox to the barVal array. For example, if there has been a value of 5 and 12 and you would trace the contents of barVal to the console using
console.log(barVal);
you would see this
Array [ 5, 12 ]
So 5 is stored at the first position and 12 at the second inside the array. With this knowledge in mind, what about adding a function which simply removes a specific element from the array? Here comes the array.splice() function into play. You can pass it an index inside the array and a number of elements it should remove.
e.g. if we want to get rid of the 12, we'd call barVal.splice(1,1);
After the element has been removed it's just a matter of updating your graph by calling draw() again. Now you might wonder why we pass 1 as the index, as we want to remove the second element - that's because indexes start counting from 0.
Here's an example:
var barVals = [];
function draw() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// calculate highest bar value (used to scale the rest)
var highest = 0;
for (var b = 0; b < barVals.length; b++) {
if (barVals[b] > highest)
highest = barVals[b];
}
// we have 8 horizontal lines so calculate an appropriate scale
var lineSpacing = 1;
var highestLine = 7 * lineSpacing;
while (highestLine < highest) {
lineSpacing *= 10;
highestLine = 7 * lineSpacing;
}
// grey background
ctx.fillStyle = "rgb(200,200,200)";
ctx.fillRect(0, 0, 600, 450);
// draw and (if we have any data to scale from) label horizontal lines
var lineNum = 0;
ctx.fillStyle = "white";
ctx.font = "16px sans-serif";
for (y = 0; y <= 350; y += 50) {
// line
ctx.beginPath();
ctx.moveTo(50, y + 50);
ctx.lineTo(550, y + 50);
ctx.stroke();
// label (the 6 is an offset to centre the text vertically on the line)
if (barVals.length > 0) {
ctx.fillText(lineSpacing * lineNum, 10, 400 - y + 6);
lineNum++;
}
}
// draw boxes (widths based on how many we have)
var barWidth = 500 / barVals.length;
var halfBarWidth = barWidth / 2;
for (b = 0; b < barVals.length; b++) {
// calculate size of box and draw it
var x = 60 + b * barWidth;
var hgt = (barVals[b] / highestLine) * 350; // as fraction of highest line
if (b % 2 == 0)
ctx.fillStyle = "red";
else
ctx.fillStyle = "blue";
ctx.fillRect(x, 400 - hgt, barWidth, hgt);
// calculate position of text and draw it
ctx.fillStyle = "white";
var metrics = ctx.measureText(barVals[b]);
var halfTextWidth = metrics.width / 2;
x = 60 + halfBarWidth + (b * barWidth) - halfTextWidth;
ctx.fillText(barVals[b], x, 420 - hgt);
}
}
function addBar() {
var textBoxObj = document.getElementById("barVal");
barVals.push(parseInt(textBoxObj.value)); // add new value to end of array. As an integer not a string!!
draw(); // redraw
textBoxObj.value = 0;
}
function removeBar() {
var textBoxObj = document.getElementById("removeBarVal");
barVals.splice(parseInt(textBoxObj.value), 1);
draw(); // redraw
}
draw();
<center>
<canvas id="canvas" width="600" height="450"></canvas>
<form>
<br>
<input type=button value='Add Bar' onclick='addBar();'> <input id='barVal' value=0>
<input type=button value='Remove Bar' onclick='removeBar();'> <input id='removeBarVal' value=0>
</form>
</center>

How to make HTML canvas' lines smoother for drawing equations

Trying to make a graphing utility. I am trying to make the lines smoother. I don't think the problem is with how I draw the lines on the canvas, but rather with how I calculate the x and y coordinates.
HTML
<canvas></canvas>
JS
const canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let c = canvas.getContext('2d');
// set the graph origin to middle of the canvas
const originX = window.innerWidth / 2;
const originY = window.innerHeight / 2;
c.strokeStyle = `rgba(240, 40, 40, 0.9)`;
c.beginPath();
c.moveTo(originX, originY);
// calculate x and y values for the equation "x^3"
for (let x = -60; x < 60; x = x + 0.1) {
let y = x**3;
draw(x, y);
}
function draw(x, y) {
// Calculated the canvas specific coordinates
let calculatedX = originX + x * 30;
let calculatedY = originY + -y * 30;
c.lineCap = "round";
c.lineWidth = 1;
// draw the line
c.lineTo(calculatedX, calculatedY);
c.stroke();
}
I tried the solutions from responds to other line-smoothing question, but they didn't work. So I think the problem is with the the for loop or the draw function.
live site: https://etasbasi.github.io/simple-grapher/dist/

Drawing in canvas with react doing weird things when rotating

I'm trying to draw in a canvas in a react component. The component draws a line and a number of squares depending on the length of an array passed to it as props inclining rotating all of them depending on another prop.
I have a loop that draws it perfectly until it reaches the 5th iteration, then something happens and it start to mess with the context restoration after the rotation. There is only one change of value in that loop ( initialX) Debugging the loop in the browser the rotate method is called the same times as the restore. I'm really confused by this behaviour, it is a very simple draw and I can't see where is my mistake.
This is what I'm getting
This is the same sketch without applying rotation
class Sketch extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
let canvas = document.getElementById("plano");
let detector = this.props.detector
let X, Y;
if (canvas && canvas.getContext && detector) {
inicializarCanvas(detector);
function inicializarCanvas(detector) {
let ctx = canvas.getContext("2d");
let s = getComputedStyle(canvas);
let w = s.width;
let h = s.height;
canvas.width = w.split("px")[0];
canvas.height = h.split("px")[0];
X = canvas.width / 2;
Y = canvas.height / 2;
//draw beam
ctx.moveTo( canvas.width / 3, canvas.height / 2);
ctx.lineTo(0, canvas.height / 2);
ctx.strokeStyle = "#f00";
ctx.stroke();
ctx.restore();
ctx.restore();
ctx.save();
drawBlades(ctx, canvas.width, canvas.height, detector)
}
function drawBlades(ctx, x, y, detector) {
let initialX = x / 3
let initialY = y / 4
let thick = 20
let margin = 5
let rotation = (90 - detector.angle) * Math.PI / 180
let i = 0
ctx.save();
let canvas = document.getElementById("plano");
let ctx2 = canvas.getContext("2d");
ctx2.save();
console.log("blade draw")
//This loop is messing up at the 5th iteration
for (; i < detector.blades.length; i++) {
ctx2.strokeStyle = "#000000";
ctx2.translate(initialX, initialY);
ctx2.rotate(rotation);
ctx2.strokeRect(0, 0, thick, y / 2);
ctx2.restore()
// this is the only variable in that changes of
// value in the loop
initialX = margin + thick + initialX
}
ctx2.save()
}
}
}
render() {
return (
<div className='sketch'>
<canvas width="400" height="150" id="plano">
Canvas not compatible with your browser
</canvas>
</div>
)
}
};
You're restoring your context in each iteration but you don't save it.
Try to add a ctx2.save() and it will work.
for (; i < detector.blades.length; i++) {
ctx2.save(); // save the context
ctx2.strokeStyle = "#000000";
ctx2.translate(initialX, initialY);
ctx2.rotate(rotation);
ctx2.strokeRect(0, 0, thick, y / 2);
ctx2.restore()
// this is the only variable in that changes of
// value in the loop
initialX = margin + thick + initialX
}

Centering on a canvas object within an HTML5 canvas

I have an Html5 canvas which i am drawing squares to.
The canvas itself is roughly the size of the window.
When i detect a click on a square i would like to translate the canvas so that the square is roughly in the center of the window. Any insights, hints, or straight-forward replies are welcome.
Here is what i tried so far:
If a square is at point (1000, 1000) I would simply translate the canvas (-1000, -1000). I know i need to add an offset so that it is centered in the window. However, the canvas always ends up off of the visible window (too far in the upper-left corner somewhere).
A more complex scenario:
Ultimately i would like to be able to center on a clicked object on a canvas that is transformed (rotated & skewed). I'm going for an isometric effect which seems to work really well. I'm wondering if this transformation affects the centering logic/math at all?
Transforming from screen to world and back
When working with non standard axis (or projections) such as isometrix it is always best to use a transformation matrix. It will cover every possible 2D projection with the same simple functions.
The coordinates of the iso world are called world coordinates. All you objects are stored as world coordinates. When you render them you project those coordinates to the screen coordinates using a transformation matrix.
The matrix, not a movie.
The matrix represents the direction and size in screen coordinates of the world
x and y axis and the screen location of the world origin (0,0)
For iso that is
x axis across 1 down 0.5
y axis across -1 down 0.5
z axis up 1 (-1 as up is the reverse of down) but this example does not use z
So the matrix as an array
const isoMat = [1,0.5,-1,0.5,0,0]; // ISO (pixel art) dimorphic projection
The first two are the x axis, the next two the y axis and the last two values are the screen coordinates of the origin.
Use the matrix to transform points
You apply a matrix to a point, this transforms the point from one coordinate system to another. You can also convert back via a inverse transform.
World to screen
You will need to convert from world coordinates to screen coordinates.
function worldToScreen(pos,retPos){
retPos.x = pos.x * isoMat[0] + pos.y * isoMat[2] + isoMat[4];
retPos.y = pos.x * isoMat[1] + pos.y * isoMat[3] + isoMat[5];
}
In the demo I ignore the origin as I set that at the center of the canvas at all times. Thus remove the origin from that function
function worldToScreen(pos,retPos){
retPos.x = pos.x * isoMat[0] + pos.y * isoMat[2];
retPos.y = pos.x * isoMat[1] + pos.y * isoMat[3];
}
Screen to world.
You will also need to convert from the screen coordinates to the world. For this you need to use the inverse transform. It's a bit like the inverse of multiply a * 2 = b is the inverse of b / 2 = a
There is a standard method for calculating the inverse matrix as follows
const invMatrix = []; // inverse matrix
// I call the next line cross, most call it the determinant which I
// think is stupid as it is effectively a cross product and is used
// like you would use a cross product. Anyways I digress
const cross = isoMat[0] * isoMat[3] - isoMat[1] * isoMat[2];
invMatrix[0] = isoMat[3] / cross;
invMatrix[1] = -isoMat[1] / cross;
invMatrix[2] = -isoMat[2] / cross;
invMatrix[3] = isoMat[0] / cross;
Then we have a function that converts from the screen x,y to the world position
function screenToWorld(pos,retPos){
const x = pos.x - isoMat[4];
const y = pos.y - isoMat[5];
retPos.x = x * invMatrix[0] + y * invMatrix[2];
retPos.y = x * invMatrix[1] + y * invMatrix[3];
}
So you get the mouse coords as screen pixels, use the above function to convert to world coords. Then you can use the world coords to find the object you are looking for.
To move a world object to the screen center you convert its coords to screen coords, add the position on the screen (the canvas center) and set the transform matrix origin to that location.
The demo
The demo creates a set of boxes in world coordinates. It sets the 2D context transform to the isoMat (isometric projection) via ctx.setTransform(
Every frame I convert the mouse screen coords to world coords then use that to check which box the mouse is over.
If the mouse button is down I then convert that box from world coords to screen and add the screen center. To smooth the step the new screen center is chased (smoothed)..
Well you should be able to work it out in the code, any problems ask in the comments.
const ctx = canvas.getContext("2d");
const moveSpeed = 0.4;
const boxMin = 20;
const boxMax = 50;
const boxCount = 100;
const boxArea = 2000;
// some canvas vals
var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
var globalTime;
const U = undefined;
// Helper function
const doFor = (count, cb) => { var i = 0; while (i < count && cb(i++) !== true); };
const eachOf = (array, cb) => { var i = 0; const len = array.length; while (i < len && cb(array[i], i++, len) !== true ); };
const setOf = (count, cb) => {var a = [],i = 0; while (i < count) { a.push(cb(i ++)) } return a };
const randI = (min, max = min + (min = 0)) => (Math.random() * (max - min) + min) | 0;
const rand = (min, max = min + (min = 0)) => Math.random() * (max - min) + min;
// mouse function and object
const mouse = {x : 0, y : 0, button : false, world : {x : 0, y : 0}}
function mouseEvents(e){
mouse.x = e.pageX;
mouse.y = e.pageY;
mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
}
["down","up","move"].forEach(name => document.addEventListener("mouse"+name,mouseEvents));
// boxes in world coordinates.
const boxes = [];
function draw(){
if(this.dead){
ctx.fillStyle = "rgba(0,0,0,0.5)";
ctx.fillRect(this.x,this.y,this.w,this.h);
}
ctx.strokeStyle = this.col;
ctx.globalAlpha = 1;
ctx.strokeRect(this.x,this.y,this.w,this.h);
// the rest is just overkill
if(this.col === "red"){
this.mr = 10;
}else{
this.mr = 1;
}
this.mc += (this.mr-this.m) * 0.45;
this.mc *= 0.05;
this.m += this.mc;
for(var i = 0; i < this.m; i ++){
const m = this.m * (i + 1);
ctx.globalAlpha = 1-(m / 100);
ctx.strokeRect(this.x-m,this.y-m,this.w,this.h);
}
}
// make random boxes.
function createBoxes(){
boxes.length = 0;
boxes.push(...setOf(boxCount,()=>{
return {
x : randI(cw- boxArea/ 2, cw + boxArea/2),
y : randI(ch- boxArea/ 2, ch + boxArea/2),
w : randI(boxMin,boxMax),
h : randI(boxMin,boxMax),
m : 5,
mc : 0,
mr : 5,
col : "black",
dead : false,
draw : draw,
isOver : isOver,
}
}));
}
// use mouse world coordinates to find box under mouse
function isOver(x,y){
return x > this.x && x < this.x + this.w && y > this.y && y < this.y + this.h;
}
var overBox;
function findBox(x,y){
if(overBox){
overBox.col = "black";
}
overBox = undefined;
eachOf(boxes,box=>{
if(box.isOver(x,y)){
overBox = box;
box.col = "red";
return true;
}
})
}
function drawBoxes(){
boxes.forEach(box=>box.draw());
}
// next 3 values control the movement of the origin
// rather than move instantly the currentPos chases the new pos.
const currentPos = {x :0, y : 0};
const newPos = {x :0, y : 0};
const chasePos = {x :0, y : 0};
// this function does the chasing
function updatePos(){
chasePos.x += (newPos.x - currentPos.x) * moveSpeed;
chasePos.y += (newPos.y - currentPos.y) * moveSpeed;
chasePos.x *= moveSpeed;
chasePos.y *= moveSpeed;
currentPos.x += chasePos.x;
currentPos.y += chasePos.y;
}
// ISO matrix and inverse matrix plus 2world and 2 screen
const isoMat = [1,0.5,-1,0.5,0,0];
const invMatrix = [];
const cross = isoMat[0] * isoMat[3] - isoMat[1] * isoMat[2];
invMatrix[0] = isoMat[3] / cross;
invMatrix[1] = -isoMat[1] / cross;
invMatrix[2] = -isoMat[2] / cross;
invMatrix[3] = isoMat[0] / cross;
function screenToWorld(pos,retPos){
const x = pos.x - isoMat[4];
const y = pos.y - isoMat[5];
retPos.x = x * invMatrix[0] + y * invMatrix[2];
retPos.y = x * invMatrix[1] + y * invMatrix[3];
}
function worldToScreen(pos,retPos){
retPos.x = pos.x * isoMat[0] + pos.y * isoMat[2];// + isoMat[4];
retPos.y = pos.x * isoMat[1] + pos.y * isoMat[3];// + isoMat[5];
}
// main update function
function update(timer){
// standard frame setup
globalTime = timer;
ctx.setTransform(1,0,0,1,0,0); // reset transform
ctx.globalAlpha = 1; // reset alpha
if(w !== innerWidth || h !== innerHeight){
cw = (w = canvas.width = innerWidth) / 2;
ch = (h = canvas.height = innerHeight) / 2;
createBoxes();
}else{
ctx.clearRect(0,0,w,h);
}
ctx.fillStyle = "black";
ctx.font = "28px arial";
ctx.textAlign = "center";
ctx.fillText("Click on a box to center it.",cw,28);
// update position
updatePos();
isoMat[4] = currentPos.x;
isoMat[5] = currentPos.y;
// set the screen transform to the iso matrix
// all drawing can now be done in world coordinates.
ctx.setTransform(isoMat[0], isoMat[1], isoMat[2], isoMat[3], isoMat[4], isoMat[5]);
// convert the mouse to world coordinates
screenToWorld(mouse,mouse.world);
// find box under mouse
findBox(mouse.world.x, mouse.world.y);
// if mouse down and over a box
if(mouse.button && overBox){
mouse.button = false;
overBox.dead = true; // make it gray
// get the screen coordinates of the box
worldToScreen({
x:-(overBox.x + overBox.w/2),
y:-(overBox.y + overBox.h/2),
},newPos
);
// move it to the screen center
newPos.x += cw;
newPos.y += ch;
}
// forget what the following function does, think it does something like draw boxes, but I am guessing.. :P
drawBoxes();
requestAnimationFrame(update);
}
requestAnimationFrame(update);
canvas { position : absolute; top : 0px; left : 0px; }
<canvas id="canvas"></canvas>

HTML Canvas - Dotted stroke around circle

I do know there is no native support for doing dotted stroke lines rendered on a canvas, but I have seen the clever ways people have been able to generate support for this.
What I am wondering is if there is any way to translate this to allow for rendering dotted strokes around shapes (specifically circles)?
the simplest way using context.setLineDash()
ctx.setLineDash([5, 5]);
ctx.beginPath();
ctx.arc(100, 60, 50, 0, Math.PI * 2);
ctx.closePath();
ctx.stroke();
Live Demo
calcPointsCirc takes 4 arguments, the center x/y, the radius, and the length of the dashes. It returns an array of points, x,y,ex,ey. You can just loop through the points to draw the dashed circle. There's probably much more elegant ways to do this but figured Id give it a shot.
function calcPointsCirc( cx,cy, rad, dashLength)
{
var n = rad/dashLength,
alpha = Math.PI * 2 / n,
pointObj = {},
points = [],
i = -1;
while( i < n )
{
var theta = alpha * i,
theta2 = alpha * (i+1);
points.push({x : (Math.cos(theta) * rad) + cx, y : (Math.sin(theta) * rad) + cy, ex : (Math.cos(theta2) * rad) + cx, ey : (Math.sin(theta2) * rad) + cy});
i+=2;
}
return points;
}
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.width = canvas.height= 200;
var pointArray= calcPointsCirc(50,50,50, 1);
ctx.strokeStyle = "rgb(255,0,0)";
ctx.beginPath();
for(p = 0; p < pointArray.length; p++){
ctx.moveTo(pointArray[p].x, pointArray[p].y);
ctx.lineTo(pointArray[p].ex, pointArray[p].ey);
ctx.stroke();
}
ctx.closePath();
If all else fails you can always loop a variable from 0 to 2*pi, skipping every step items and drawing on every other step items points at sin(angle)*radius+centerx, cos(angle)*radius+centery.
There you go, home-made dotted circle :)
My JavaScript Path library implements dashed and dotted drawing of arbitrary paths (which can be composed of any number of straight or curved segments), including ellipses. Download it and check out the examples.
I was looking for a dashed-circle for my game and after reading all of the pages I have written a class in typescript it works very well. If anybody looks for the dashed-circle in typescript, it is here;
export class DashedCircle
{
centerX: number;
centerY: number;
radius: number;
color: string;
dashSize: number;
ctx: CanvasRenderingContext2D;
constructor(ctx:CanvasRenderingContext2D, centerX: number, centerY: number, radius: number, color: string, dashSize: number)
{
this.ctx = ctx;
this.centerX = centerX;
this.centerY = centerY;
this.radius = radius;
this.color = color;
this.dashSize = dashSize;
}
CalculateCirclePoints()
{
var n = this.radius / this.dashSize;
var alpha = Math.PI * 2 / n;
var pointObj = {};
var points = [];
var i = -1;
while (i < n)
{
var theta = alpha * i;
var theta2 = alpha * (i + 1);
points.push({
x: (Math.cos(theta) * this.radius) + this.centerX,
y: (Math.sin(theta) * this.radius) + this.centerY,
ex: (Math.cos(theta2) * this.radius) + this.centerX,
ey: (Math.sin(theta2) * this.radius) + this.centerY });
i += 2;
}
return points;
}
Draw()
{
var points = this.CalculateCirclePoints();
this.ctx.strokeStyle = this.color;
this.ctx.beginPath();
for (var p = 0; p < points.length; p++)
{
this.ctx.moveTo(points[p].x, points[p].y);
this.ctx.lineTo(points[p].ex, points[p].ey);
this.ctx.stroke();
}
this.ctx.closePath();
}
}