[英]HTML5 Canvas - Drawing a line inside a circle at specific angle
Javascript Javascript
var canvas = document.getElementById("mycanvas");
draw(canvas);
function draw(canvas){
var context = canvas.getContext('2d'), centerX = Math.floor(canvas.width / 2), centerY = Math.floor(canvas.height / 2),radius = Math.floor(canvas.width / 2);
context.lineWidth = 1;
context.strokeStyle = 'black';
var begin = 0; interval = 90;
var arcSize= degreesToRadians(interval);
for(var startingAngle=begin; startingAngle < 360;){
context.beginPath();
context.moveTo(centerX, centerY);
context.arc(centerX, centerY, radius, degreesToRadians(startingAngle), startingAngle + arcSize, false);
context.closePath();
context.stroke();
startingAngle = startingAngle + interval;
}
lineAtAngle(context,centerX,centerY,radius,30);
}
function degreesToRadians(degrees) {
return (degrees * Math.PI)/180;
}
function lineAtAngle(context,x1, y1, length, angle) {
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x1 + length * degreesToRadians(angle), y1 + length * degreesToRadians(angle));
context.strokeStyle = 'red';
context.closePath();
context.stroke();
}
HTML HTML
<canvas id="mycanvas" width="400" height="400"></canvas>
What I am trying to achieve Pass the value of angle at which the red line needs to be drawn and it should be drawn at that angle.我想要实现的是传递需要绘制红线的角度值,并且应该以该角度绘制。
I have managed to achieve it with following code.我已经设法通过以下代码实现了它。 A bit hacky but it works.有点hacky,但它有效。 Not sure why I need to multiple the angle by -1.不知道为什么我需要将角度乘以 -1。
var canvas = document.getElementById("mycanvas");
draw(canvas, 167);
function draw(canvas, angle){
var context = canvas.getContext('2d'), centerX = Math.floor(canvas.width / 2), centerY = Math.floor(canvas.height / 2),radius = Math.floor(canvas.width / 2);
context.lineWidth = 1;
context.strokeStyle = 'red';
var begin = 0; interval = 90;
var arcSize= degreesToRadians(interval);
context.beginPath();
context.moveTo(centerX,centerY);
context.arc(centerX,centerY,radius, degreesToRadians(0), degreesToRadians((-1) * angle),false);
context.closePath();
context.stroke();
context.strokeStyle = 'black';
context.lineWidth = 2;
for(var startingAngle=begin; startingAngle < 360;){
context.beginPath();
context.moveTo(centerX, centerY);
context.arc(centerX, centerY, radius, degreesToRadians(startingAngle), startingAngle + arcSize, false);
context.closePath();
context.stroke();
startingAngle = startingAngle + interval;
}
}
function degreesToRadians(degrees) {
return (degrees * Math.PI)/180;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.