我希望图像在单击时旋转。图像应该顺时针旋转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,transparent,transparent 49px,#88F 49px,#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;
}
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tetris(test2)</title>
<link rel="stylesheet" href="styleSheets/main.css">
<script src = "https://code.jquery.com/jquery-3.4.1.js"></script>
<script src = "js/jquery.1.js"></script>
<script src = "js/main.js"></script>
</head>
<body>
<div id="container" onclick= "rotate()" style= "height: 650px; width: 500px; background: black; position: relative">
<div id= "left" onclick= "moveLeft()"></div>
<div id= "right" onclick= "moveRight()"></div>
</div>
<div class= "grid"></div>
</body>
答案 0 :(得分:1)
通过CSS在要旋转的元素上设置变换原点。
例如,
transform-origin: top left;
也可以在此处查看更多文档:https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin
答案 1 :(得分:1)
您需要转换原始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进行样式设计