作者:书友23295799 | 来源:互联网 | 2023-10-12 16:11
我希望图像在单击时旋转。图像应该顺时针旋转90度。但是,当我希望它在灰色矩形的右上角旋转时,枢轴点当前位于元素的中心内。任何建议或指导将不胜感激。
var svgNS = "http://www.w3.org/2000/svg";
var htmlNS = "http://www.w3.org/1999/xhtml";
function createShape() {
var cOntainer= document.getElementById("container");
var outer = document.createElementNS(svgNS,"svg");
container.append(outer);
outer.id = "outer"
console.log(outer.id)
outer.style.background = "grey";
outer.style.height = "100px";
outer.style.width = "150px";
outer.style.left = "150px";
outer.style.top = "200px";
outer.style.position = "absolute";
var shape1 = document.createElementNS(svgNS,"rect");
outer.append(shape1);
shape1.style.width = "100%";
shape1.style.height = "50%";
shape1.style.fill = "orange";
var shape2 = document.createElementNS(svgNS,"rect");
outer.append(shape2);
shape2.style.width = "33.33%";
shape2.style.height = "100%";
shape2.style.fill = "orange";
}
window.Onload= createShape;
window.Onclick= rotate;
function rotate() {
var outer = document.getElementById("outer");
console.log(outer.style.background)
outer.style.transform = "rotate(90deg)";
}
.grid {
background-image: repeating-linear-gradient(0deg,transparent,transparent 49px,#88F 49px,#88F 50px),repeating-linear-gradient(-90deg,#88F 50px);
background-size: 50px 50px;
top: 8px;
height: 651px;
position: absolute;
width: 501px;
}
#left {
top: 0px;
width: 250px;
height: 650px;
position: absolute;
background: transparent;
}
#right {
left: 250px;
top: 0px;
width: 250px;
height: 650px;
position: absolute;
background: transparent;
}
通过CSS在要旋转的元素上设置变换原点。
例如,
transform-origin: top left;
也可以在此处查看更多文档:https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin
,
您需要转换原始CSS属性!
对于Javascript:https://www.w3schools.com/jsref/prop_style_transformorigin.asp
对于CSS:https://www.w3schools.com/cssref/css3_pr_transform-origin.asp
您可以将以下内容应用于outer
元素:
outer.style.transformOrigin = "left top";
只需将其与其余样式一起放在createShape()
函数中
我还建议您每次创建元素时都使用CSS而不是Javascript进行样式设计