2010-09-15 181 views
0

我在畫布上有一個動畫,其中有一些圖像(使用drawImage()繪製)。爲了簡單起見,假設只有兩個圖像。這些圖像遵循人造三維空間中的圓形路徑,以便有時一個圖像與另一個圖像重疊,而其他時候第二個圖像與第一個圖像重疊。這些圖像也隨着從觀看者「更近」或「更遠」移動而縮放。確定在畫布上繪製的圖像的尺寸以及鼠標位於圖像上時的尺寸

每個這些圖像是用下面的(簡化的)代碼的對象:

function slide_object() { 
    this.x = 0.0; // x = position along path (in radians) 
    this.xpos = 0.0; // x position on canvas 
    this.ypos = 0.0; // y position on canvas 
    this.scale = 0.0; 
    this.name = ""; // a string to be displayed when slide is moused over 
    this.imgx = 0.0; // width of original image 
    this.imgy = 0.0; // height of original image 

    this.init = function (abspath, startx, name) { // startx = path offset (in radians) 
     this.name = name; 
     this.x = (startx % (Math.PI * 2)); 
     var slide_image = new Image(); 
     slide_image.src = abspath; 
     this.img = slide_image; 
     calcObjPositions(0, this); // calculate's the image's position, then draws it 
    }; 
    this.getDims = function() { // called by calcObjPositions when animation is started 
     this.imgx = this.img.width/2; 
     this.imgy = this.img.height/2; 
    } 
} 

這些對象中的每一個存儲在數組中稱爲slides

爲了適當地重疊圖像,drawObjs函數首先在排序的slides[i].scale順序slides陣列從最小到最大,然後繪製圖像開始slides[0]

$(document).ready()我運行一個init功能,除其他事項外,將一個事件偵聽到畫布:

canvas = document.getElementById(canvas_id); 
canvas.addEventListener('mousemove', mouse_handler, false); 

這個處理器的目的是,以確定鼠標和鼠標是否已經結束其中一張幻燈片(它將通過jQuery修改頁面上的<div>)。

這是我的問題 - 我試圖找出如何確定鼠標在任何給定時間結束。從本質上講,我需要的代碼填寫以下邏輯(在mouse_handler()功能最有可能的):

// if (mouse is over a slide) { 
//  slideName = get .name of moused-over slide; 
// } else { 
//  slideName = ""; 
// } 
// $("#slideName").html(slideName); 

有什麼想法?

回答

0

看起來我只需要一些睡眠,然後才能找出這一個。

我已經掌握了我需要的一切來確定圖像的大小,並將它放置在畫布上。

我增加了以下功能我slide_object

this.getBounds = function() { 
     var bounds = new Array(); 
     bounds[0] = Math.ceil(this.xpos); // xmin 
     bounds[1] = bounds[0] + Math.ceil(this.imgx * this.scale); // xmax 
     bounds[2] = Math.ceil(this.ypos); // ymin 
     bounds[3] = bounds[2] + Math.ceil(this.imgy * this.scale); // ymax 
     return bounds; 
    }; 

然後在我的mouse_handler功能,我從一個功能我叫isWithinBounds()當前鼠標懸停幻燈片這需要一個鼠標X和鼠標指數y位置:

function isWithinBounds(mx,my) { 
    var index = -1; 
    for (var i in slides) { 
     bounds = slides[i].getBounds(); 
     if ((mx >= bounds[0] && mx <= bounds[1]) && (my >= bounds[2] && my <= bounds[3])) { 
      index = i; 
     } 
    } 
    return index; 
} 

由於slides規模的順序進行排序,從小到大,每次迭代都會更換或維護的index值。如果有多個圖片佔據空間,則會返回最上面的幻燈片index

現在唯一的問題是弄清楚如何使代碼更有效率。 Chrome運行動畫沒有任何滯後。 Firefox有一些,我甚至沒有想過爲IE用戶實現excanvas.js。對於缺乏畫布支持的瀏覽器,畫布對象只能用display:none隱藏。