我需要能够多次缩放div,并且可以改变原点。
请查看:http://jsfiddle.net/croydufixe/vdXM7/(请参阅下面的完整代码)
当这个小提琴运行时,会出现一个灰色正方形,其中红色网格将正方形划分为4 x 4。
红色标记位于下一个变换的“原点”。
在框架的顶部,您可以看到两个按钮“+”和“ - ”,将灰色方块缩小一个因子,增加(或减少)0.5
现在,请使用以下步骤:
我不明白步骤3中使用的来源(上/左而不是25%/ 25%)
感谢您的帮助。
完整代码:
<head>
<title></title>
<script>
var lastScale=1;
var originModified = false;
function drawCanvas()
{
var canevas=document.getElementById("canvas");
var ctx = canevas.getContext("2d");
var e=document.getElementById("canvas");
var largeur = e.offsetWidth;
var hauteur = e.offsetHeight;
for( var x=0; x<largeur; x+=largeur/4 )
{
ctx.moveTo( x, 0 );
ctx.lineTo( x, hauteur );
}
for( var y=0; y<hauteur; y+=hauteur/4 )
{
ctx.moveTo( 0, y );
ctx.lineTo( largeur, y );
}
ctx.strokeStyle = '#ff0000';
ctx.stroke();
}
function init( )
{
lastScale=1;
originModified=false;
var e = document.getElementById( "origin" );
}
function incrementalScale( increment )
{
var e=document.getElementById("a");
var eOrigin = document.getElementById("origin");
//
var targetOriginX = eOrigin.offsetLeft;
var targetOriginY = eOrigin.offsetTop;
e.style.transformOrigin = targetOriginX + "px " + targetOriginY + "px 0px";
lastScale += increment;
var transform = "scale(" + lastScale + ")";
e.style.transform = transform;
originModified = false;
}
function setOrigin(event)
{
if( originModified )
{
alert( 'origin already modified : please do a scale');
return;
}
var eOrigin=document.getElementById("origin");
var ee = document.getElementById("a");
var deltaX = eOrigin.offsetLeft - ( event.clientX - ee.offsetLeft );
eOrigin.style.left = ( eOrigin.offsetLeft - deltaX / lastScale ) + "px";
var deltaY = eOrigin.offsetTop - ( event.clientY - ee.offsetTop );
eOrigin.style.top = ( eOrigin.offsetTop - deltaY / lastScale ) + "px";
originModified = true;
}
</script>
</head>
<body onload="drawCanvas();init();">
<div>
scale <input type="button" onclick="incrementalScale(+0.5)" value="+">
<input type="button" onclick="incrementalScale(-0.5)" value="-">
</div>
<div id="a" style="position:relative;top:400px;left:400px;border:1 px solid red;background-color:#DDD;width:200px;height:200px"
onmousedown="setOrigin(event);">
<canvas id="canvas" width="200px" height="200px"></canvas>
<div id="origin" style="position:absolute;top:100px;left:100px;width:5px;height:5px;background-color:red">
</div>
</div>
</body>