2015-09-14 45 views
0

我正在進行心理學研究的申請。在某些特定情況下,Web應用程序需要在很短的時間內(如20-50ms)顯示圖像。什麼是在網站上顯示圖像很短時間內最快,最穩定的方式?

從互聯網加載圖像不是一個問題,因爲程序會在使用以下腳本進入網站時緩存所有圖像。

for stimulus in stimuli 
    if stimulus 
     extension = stimulus.split(".").pop() 
     if extension.match(/png|jpg|jpeg|gif|bmp/i) 
     # Pre-cache every image to the browser by creating dummy image DOMs 
     image = $("<img src='#{stimulus}' style='display:none;'></img>") 
     $(document.body).append(image) 

然而,問題是如下:當我的圖像DOM追加到容器,計時器功能將被立即創建,指定時間後(如10ms)的函數將刪除圖像DOM並顯示下一個圖片。當超時時間足夠長(> 100ms)時,此功能可以完美工作,但如果超時時間非常短(如10-50ms),則有時圖像不會顯示在屏幕上。我目前的工作是在圖像被刪除之前的幾毫秒內應用不透明動畫。不僅這不是一個好方法,有時候(主觀觀察)圖像會顯示更長時間,有時顯示更短。

# Call render function to get the image DOM 
    $("#stimulus-container").append(stimulus.render(_i + 1, stimuli.length)) 
    if maxTimeout > 0 
    nextTimer = setTimeout(-> 
     clearTimeout(nextTimer) 
     # Current (bad) workaround defer the removal of the image DOM 
     $("#stimulus-container *").animate({ 
     opacity: 0, 
     }, 50,() -> 
     # Remove current image and display next 
     playStimulus(nextSequence) 
    ) 
    # The designated time to display the image 
    , maxTimeout 
    ) 

我認爲這個問題可能與DOM操作的延遲有關。我的代碼是否有很好的解決方法,或者我應該使用其他方法(如CSS動畫/ Canvas)來重新實現?我對這些(CSS動畫/畫布)不熟悉,因此任何細節建議實施將不勝感激。關鍵是要在屏幕上顯示一個非常短暫(穩定)的圖像。非常感謝您的關注。

回答

2

你說得對,DOM潛伏期有時可能太高,特別是對於像這樣短時間內的操縱。但是,您可以只使用一個DOM圖像元素,預先加載所有需要的圖像,並且每20ms更改圖像的src屬性。

我編了一個簡短的演示給你:http://codepen.io/cgav/pen/MaKbJg?editors=101

HTML:

<img id="image" /> 

JS:

allImages = [] 
urls = [ 
    # the images' URLs go in here 
] 

DURATION = 10 

startTimer = -> 
    domImage = document.getElementById("image") 
    counter = 0 
    setInterval -> 
    domImage.src = allImages[counter].dataurl 
    counter++ 
    counter = 0 if counter is allImages.length 
    , DURATION 

storeNextDataURLFromImage =() -> 
    url = urls.pop() 
    if not url? 
    return startTimer() 

    img = new Image() 
    img.crossOrigin = "Anonymous" # this is needed to avoid http://stackoverflow.com/questions/22710627/tainted-canvases-may-not-be-exported 
    img.onload = (e) -> 
    canvas = document.createElement("canvas") 
    canvas.width = img.width 
    canvas.height = img.height 

    ctx = canvas.getContext("2d") 
    ctx.drawImage(img, 0, 0) 
    allImages.push { 
     dataurl: canvas.toDataURL() 
     width: img.width 
     height: img.height 
    } 
    storeNextDataURLFromImage() 

    img.src = url 

storeNextDataURLFromImage() 
相關問題