簡體   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