我有一个4点绘制的矩形。我需要旋转所有点的任意程度,并找到新的x,y
的points.I尝试旋转这些,但问题是当我会增加程度,矩形变得更小,当我会降低程度,第一个矩形不再绘制。我如何通过使用Angular来做到这一点。使用Angular旋转矩形4点
<div ng-app="myApp">
<div ng-app="myApp" ng-controller="rectController">
<input type="number" ng-model="Rotation" min="-360" max="360" value="0"/>
<rect-rotate/>
</div>
</div>
下面是JavaScript代码:
var App = angular.module('myApp', []);
var Ctrl = App.controller('rectController', function($scope) { });
Ctrl.directive('rectRotate', function() {
function link(scope, el, attr) {
var w = 1200, h = 780;
var width = 300, height = 200;
var point1=[300,200],point2=[600,200],point3=[600,400],point4=[300,400];
var svg = d3.select(el[0]).append("svg")
.attr("width", w)
.attr("height", h);
var newg = svg.append("g").data([{ x: width, y: height }]);
var rect = newg.append("path")
.attr("x", function(d) {
return d.x;
})
.attr("y", function(d) {
return d.y;
})
.attr("fill-opacity", .5)
.attr("d", function(d) {
var dCommand
= "M" + point1[0] + "," + point1[1] + "L" + point2[0]
+ "," + point2[1] + "L " + point3[0] + "," + point3[1]
+ "L " + point4[0] + "," + point4[1] + "Z";
return dCommand;
});
scope.$watch('Rotation', function (newValues) {
var rotateAngle = newValues;
rotateAngle = rotateAngle * Math.PI/180.0;
var centerX = (point1[0]+point3[0])/2;
var centerY = (point1[1]+point3[1])/2;
//1
point1[0] = (Math.cos(rotateAngle) * (point1[0] - centerX)
-(Math.sin(rotateAngle) * (point1[1] - centerY)) + centerX;
point1[1] = (Math.sin(rotateAngle) * (point1[0] - centerX))
+(Math.cos(rotateAngle) * (point1[1] - centerY)) + centerY;
//2
point2[0] = (Math.cos(rotateAngle) * (point2[0] - centerX)
-(Math.sin(rotateAngle) * (point2[1] - centerY)) + centerX;
point2[1] = (Math.sin(rotateAngle) * (point2[0] - centerX))
+(Math.cos(rotateAngle) * (point2[1] - centerY)) + centerY;
//3
point3[0] = (Math.cos(rotateAngle) * (point3[0] - centerX)
-(Math.sin(rotateAngle) * (point3[1] - centerY)) + centerX;
point3[1] = (Math.sin(rotateAngle) * (point3[0] - centerX))
+(Math.cos(rotateAngle) * (point3[1] - centerY)) + centerY;
//4
point4[0] = (Math.cos(rotateAngle) * (point4[0] - centerX)
-(Math.sin(rotateAngle) * (point4[1] - centerY)) + centerX;
point2[1] = (Math.sin(rotateAngle) * (point4[0] - centerX))
+(Math.cos(rotateAngle) * (point4[1] - centerY)) + centerY;
rect.attr("d", function (d) {
var dCommand
= "M" + point1[0] + "," + point1[1] + "L" + point2[0]
+ "," + point2[1] + "L " + point3[0] + "," + point3[1]
+ "L " + point4[0] + "," + point4[1] + "Z";
return dCommand;
});
}return {
link: link
};
});
你可以简单地使用'transform'用'旋转属性()'值,无需计算自己的旋转。 –
恐怕我需要用d值创建路径以保持其他格式。具有rotate()值的transform属性将按左上角的旋转矩形旋转矩形,并将其移动。我需要以中心为中心旋转并保持协调。 – Gabriel
你可以指定旋转点 - https://developer.mozilla.org/en/docs/Web/SVG/Attribute/transform –