为什么我的HTML画布不能旋转?

时间:2015-07-14 05:44:27

标签: javascript html5 canvas

Canvas脚本:

function clock_hand_hh(hh) {
    var hh_canvas = document.getElementById('clock_hand_hh');
    var hh_context = hh_canvas.getContext('2d');
    hh_canvas.width = 500;
    hh_canvas.height = 500;
    var centerX = hh_canvas.width / 2;
    var centerY = hh_canvas.height / 2;
    var radius = 10;

    hh_context.beginPath();
    hh_context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    hh_context.fillStyle = '#000000';
    hh_context.fill();
    hh_context.lineWidth = 5;
    hh_context.strokeStyle = '#000000';
    hh_context.stroke();

    hh_context.beginPath();
    hh_context.bezierCurveTo(centerX, centerY, centerX - 10, centerY - 50, centerX, centerY - 100);
    hh_context.bezierCurveTo(centerX, centerY-100, centerX + 10, centerY - 50, centerX, centerY);
    hh_context.fillStyle = '#000000';
    hh_context.fill();
    hh_context.lineWidth = 2;
    hh_context.strokeStyle = '#000000';
    hh_context.stroke();   

    if (hh > 12) {
        hh = hh - 12;
    }
    //alert((hh / 12) * 2 * Math.PI);
    hh_context.translate(centerX, centerY);
    hh_context.rotate((hh / 12) * 2 * Math.PI); 
}

注意:警报(我评论过)显示画布所需的旋转角度的正确值(以弧度表示)。

2 个答案:

答案 0 :(得分:1)

翻译或旋转上下文时,表示您移动并旋转要使用的坐标系。它不会影响已经绘制的图像。

您需要做的是在开始绘图之前修改坐标系。因此,只需在第一个beginPath()语句之前移动以下两行。

hh_context.translate(centerX, centerY);
hh_context.rotate((hh / 12) * 2 * Math.PI); 

答案 1 :(得分:1)

你只需移动两次:使用center变量绘制,然后移动坐标......

    function clock_hand_hh(hh) {
        var hh_canvas = document.getElementById('clock_hand_hh');
        var hh_context = hh_canvas.getContext('2d');
        hh_canvas.width = 500;
        hh_canvas.height = 500;
        var centerX = hh_canvas.width / 2;
        var centerY = hh_canvas.height / 2;
        var radius = 10;

        hh_context.translate(centerX, centerY);
        hh_context.rotate((hh / 12) * 2 * Math.PI); 

        hh_context.beginPath();
        hh_context.arc(0, 0, radius, 0, 2 * Math.PI, false);
        hh_context.fillStyle = '#000000';
        hh_context.fill();
        hh_context.lineWidth = 5;
        hh_context.strokeStyle = '#000000';
        hh_context.stroke();


        hh_context.beginPath();
        hh_context.bezierCurveTo(0, 0, -10, -50, 0, -100);
        hh_context.bezierCurveTo(0, -100, 10, -50, 0, 0);
        hh_context.fillStyle = '#000000';
        hh_context.fill();
        hh_context.lineWidth = 2;
        hh_context.strokeStyle = '#000000';
        hh_context.stroke();   

        if (hh > 12) {
            hh = hh % 12 + 1;
        }
        //alert((hh / 12) * 2 * Math.PI);
    }

clock_hand_hh(4);
<canvas id="clock_hand_hh" style="width: 200px; height: 200px;"></canvas>