14
在測試應用程序中,我有一個簡單的矩形畫布。每100ms調用一次方法繪製。縮放畫布
從代碼中我可以看到,我使用鼠標滾輪來縮放一切。現在發生的情況是,所有東西都被縮放,但是當矩形的大小爲10px,10px,並且鼠標右移時,縮放後矩形不再位於鼠標下面。 (這當然是對的,因爲所有單位都按比例放大到了
但是我想要的是,mouseposition是「縮放行動的中心」,就像在google地圖中一樣,所以鼠標之前的內容。結垢,是根據鼠標之後,以及我做了幾attemps帶翻譯,但我想不通,怎麼做
在此先感謝
這裏是我的代碼:
<script type="text/javascript">
var scroll = 0;
var scale = 1.0;
/** This is high-level function.
* It must react to delta being more/less than zero.
*/
function handle(delta) {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
scroll = delta;
if(scroll > 0)
{
scale += 0.2;
}
if(scroll < 0)
{
scale -= 0.2;
}
}
/** Event handler for mouse wheel event.
*/
function wheel(event){
var delta = 0;
if (!event) /* For IE. */
event = window.event;
if (event.wheelDelta) { /* IE/Opera. */
delta = event.wheelDelta/120;
} else if (event.detail) { /** Mozilla case. */
/** In Mozilla, sign of delta is different than in IE.
* Also, delta is multiple of 3.
*/
delta = -event.detail/3;
}
/** If delta is nonzero, handle it.
* Basically, delta is now positive if wheel was scrolled up,
* and negative, if wheel was scrolled down.
*/
if (delta)
handle(delta);
/** Prevent default actions caused by mouse wheel.
* That might be ugly, but we handle scrolls somehow
* anyway, so don't bother here..
*/
if (event.preventDefault)
event.preventDefault();
event.returnValue = false;
}
/** Initialization code.
* If you use your own event management code, change it as required.
*/
if (window.addEventListener)
/** DOMMouseScroll is for mozilla. */
window.addEventListener('DOMMouseScroll', wheel, false);
/** IE/Opera. */
window.onmousewheel = document.onmousewheel = wheel;
var drawX = 0;
var drawY = 0;
var overX = 0;
var overY = 0;
function startCanvas()
{
var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
setInterval(draw,100);
}
function draw()
{
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0,0,window.innerWidth,window.innerHeight);
ctx.save();
ctx.scale(scale,scale);
ctx.fillRect(drawX,drawY,20,20);
//ctx.translate(-scale,-scale);
ctx.restore();
ctx.font="20pt Arial";
ctx.fillText(scale+":"+drawX,0,150);
}
function canvasClick(event)
{
console.log(event.layerX+"/"+scale);
drawX = event.layerX/scale;
drawY = event.layerY/scale;
}
function canvasOver(event)
{
console.log("over");
overX = event.layerX;
overY = event.layerY;
}
</script>
謝謝......我會仔細看看它。很高興聽到,這是一個不平凡的數學事物,我在紙上畫圖,並不能找出如何計算它:-D – Chris
太棒了!謝謝,非常好! – Chris