使用Canvas在radarplot中旋转箭头

时间:2011-07-27 15:29:40

标签: php html5 canvas html5-canvas

我正在尝试将箭头添加到我在Canvas中编码的雷达/蜘蛛图中。因为我使用PHP / SQL来检索一些数据库值,所以我回应了大部分需要的JS来在Canvas上绘制它。到目前为止,我已经绘制了轴(7)和指南(5个值)。

如何旋转箭头使它们正确显示;有一个角度和7轴的末端?

function drawArrows(context){
    context.beginPath();
    context.strokeStyle = "#ccc";
    context.lineWidth = 2;
    context.save();
<?php
$arrowHoek = 35;
$cHoek = (360/7);
$arrowLength = 10;

for ($i = 1 ; $i < 8 ; $i++) {
    $arrow_xleft = round((getCoordinates($i,6,x))-(sin(deg2rad($arrowHoek))*$arrowLength),2);
    $arrow_yleft = round((getCoordinates($i,6,y))+(cos(deg2rad($arrowHoek))*$arrowLength),2);
    $arrow_xright = round((getCoordinates($i,6,x))+(sin(deg2rad($arrowHoek))*$arrowLength),2);
    $arrow_yright = $arrow_yleft;
    $arrow_rotation = deg2rad(($cHoek*$i)-$cHoek);      

    echo "\tcontext.moveTo(";   
    getCoordinates($i,6,null);
    echo ");\n";
    echo "\tcontext.lineTo($arrow_xleft, $arrow_yleft);";
    echo "\n\tcontext.moveTo(";
    getCoordinates($i,6,null);
    echo ");\n";
    echo "\tcontext.lineTo($arrow_xright, $arrow_yright);\n";
    echo "\tcontext.rotate($arrow_rotation);\n";
    echo "\tcontext.restore();\n";
    echo "\tcontext.save();\n"; 

} 
?>
context.stroke();
}

1 个答案:

答案 0 :(得分:0)

似乎我已经解决了!如在其他主题中所见,它使用save(),translate(),rotate()和restore()函数。如果你将它放在一个单独的Javascript函数中,你可以对各个Canvas部件进行转换,而不会弄乱任何其他图纸。

下面是解决方案(请注意,这使用PHP来回显Javascript函数)。

function drawArrows(context){
context.beginPath();
context.strokeStyle = "#ccc";
context.lineWidth = 2;
<?php
$arrowHoek = 35;
$cHoek = (360/7);
$arrowLength = 10;

for ($i = 1 ; $i < 8 ; $i++) {
    $arrow_xleft = -(sin(deg2rad($arrowHoek))*$arrowLength);
    $arrow_yleft = (cos(deg2rad($arrowHoek))*$arrowLength);
    $arrow_xright = (sin(deg2rad($arrowHoek))*$arrowLength);
    $arrow_yright = $arrow_yleft;
    $arrow_rotation = deg2rad(($cHoek*$i)-$cHoek);  

    echo "\tcontext.save();\n";
    echo "\tcontext.translate(";    
    getCoordinates($i,6,null);
    echo ");\n";
    echo "\tcontext.rotate($arrow_rotation);\n";
    echo "\tcontext.moveTo($arrow_xleft, $arrow_yleft);";
    echo "\n\tcontext.lineTo(0,0);\n";
    echo "\tcontext.lineTo($arrow_xright, $arrow_yright);\n";
    echo "\tcontext.restore();\n";
} 
?>
context.stroke();
}
  • 注意:context和canvas元素的声明都在容器函数中。