如何在画布中旋转形状,html5?

时间:2011-05-14 00:01:02

标签: javascript html5 canvas

我试图用这个

旋转一条线
window.onload= function(){
        var canvas=document.getElementById("foo");
        var context=canvas.getContext("2d");

        context.moveTo(250, 50);
        context.lineTo(250, 250);
        context.stroke();
        context.rotate(0.30);

    };
我在做错了什么?我想我错过了一些步骤。任何人都可以解释一下吗?

3 个答案:

答案 0 :(得分:26)

rotate()实际上旋转了整个坐标系。默认为0,0(画布的左上角)。你需要按照这些方针做点什么:

context.save(); // saves the coordinate system
context.translate(250,50); // now the position (0,0) is found at (250,50)
context.rotate(0.30); // rotate around the start point of your line
context.moveTo(0,0) // this will actually be (250,50) in relation to the upper left corner
context.lineTo(0,200) // (250,250)
context.stroke();
context.restore(); // restores the coordinate system back to (0,0)

查看此链接,以获得有关translate()和rotate()如何工作的非常好的解释: tutsplus tutorial

史蒂夫

答案 1 :(得分:6)

请改用:

context.rotate(0.30); // <<< set current transformation to rotated
context.moveTo(250, 50);
context.lineTo(250, 250);
context.stroke();

答案 2 :(得分:0)

import sys
import unittest
import logging
from histogram import Histogram
class TestHistogram(unittest.TestCase):

def test_case2(self):
    h = Histogram([2,1,2])
    self.assertEqual(h.calculateMaxAreaON(), 3)

if __name__ == '__main__':
    argv = len(sys.argv) > 1 and sys.argv[1]
    loglevel = logging.INFO if argv == '-v' else logging.WARNING
    logging.basicConfig(level=loglevel)
    unittest.main() 

context.rotate((Math.PI / 180) * 25); //Rotate the canvas by 25 degrees