根据x和y轴执行变换

时间:2015-04-21 10:51:52

标签: javascript html5 html5-canvas

我正在开发一个绘图应用程序,用户可以通过单击按钮绘制最多9个边的多边形,然后对绘制的形状执行转换,但我无法将转换正确映射到x和y轴(取决于用户对轴的选择)。 这是我的旋转功能代码:

function rotate()
{
    polygonSides = document.getElementById("polygonSide").value;
    var coordinates = [],
    radius = Math.sqrt(Math.pow((50), 2) + Math.pow((50), 2)),
    index = 0;
    var angle = 0 * (Math.PI / 180);

    for (index = 0; index < polygonSides; index++) {
        coordinates.push({x: -200 + radius * Math.cos(angle), y: -100 - radius * Math.sin(angle)});
        angle += (2 * Math.PI) / polygonSides;
    }

    var rad = prompt("Enter angle in radians: ","");
    var rad = prompt("Enter x or y axis: ","x or y"); //how to use this to map?

    context.translate(canvas.width / 5, canvas.height / 5); //not working with value 2


    context.rotate(Math.PI / rad);

    context.beginPath();
    context.moveTo(coordinates[0].x, coordinates[0].y);
    for (index = 1; index < polygonSides; index++) {
        context.lineTo(coordinates[index].x, coordinates[index].y);
    }

    context.closePath();
    context.stroke();
    context.strokeStyle = strokeColor.value;

}

画布中心的轴为(0,0)。当我用弧度4旋转时,我将其作为输出: enter image description here

如何修改我的代码以适应基于x或y轴的旋转?

2 个答案:

答案 0 :(得分:0)

你可以使用jQuery来应用css。 示例

var $canvas = $("#bkgimg");
rotate(45);

    function rotate(degree) {
  // For webkit browsers: e.g. Chrome
       $canvas.css({ WebkitTransform: 'rotateX(' + degree + 'deg)'});
  // For Mozilla browser: e.g. Firefox
       $canvas.css({ '-moz-transform': 'rotateX(' + degree + 'deg)'});
    }

答案 1 :(得分:0)

你可以使用

div {
    -ms-transform: rotate(7deg); /* IE 9 */
    -webkit-transform: rotate(7deg); /* Chrome, Safari, Opera */
    transform: rotate(7deg);
}

如果您使用的是css3,那么您可以使用translateX和translateY