繁体   English   中英

HTML5 Canvas - 在特定角度的圆内画一条线

[英]HTML5 Canvas - Drawing a line inside a circle at specific angle

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

<canvas id="mycanvas" width="400" height="400"></canvas>

JSFiddle

我想要实现的是传递需要绘制红线的角度值,并且应该以该角度绘制。

在此处输入图片说明

我已经设法通过以下代码实现了它。 有点hacky,但它有效。 不知道为什么我需要将角度乘以 -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;
}

JSFiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM