2013-09-10 46 views
2

我想要一個汽車的圖像,當用戶點擊汽車上的一個點時,我會在該點上放下一個x圖像或一個圓形圖像。我需要保存他們點擊的位置,以便在他們回來時將它顯示在同一個位置。如何讓用戶在html中將圖片置於另一張圖片之上?

在html中這樣做的最好方法是什麼?

我應該使用一個圖像與其上覆蓋的其他圖像?

我應該使用html5嗎?

任何人都知道任何類似性質的工作示例?

想要使用js,html5等在iphone safari(非本地應用程序)上進行這項工作。應用程序在rails上是ruby,所以我可以利用一些服務器端功能,但如果可能的話,寧願在html/css中儘可能多地利用它。

+0

你是僅限於像JavaScript,HTML和CSS只有客戶端技術? –

+0

是的,將編輯澄清,謝謝,目標是做到這一點在safari的iphone理想使用html5,js和iui(或其他類似的) – Joelio

+0

作爲一個出發點:http://stackoverflow.com/questions/19461/click -an-image-get-coordinates和http://css-tricks.com/examples/ShapesOfCSS/ – ChrisW

回答

4

您可以使用canvas元素來執行此操作。 canvas元素允許您爲其繪製圖像和形狀。

要存儲和檢索點擊,您可以使用網絡存儲localStorage)。

例如 - 加載圖像,並描繪到帆布:

ONLINE DEMO HERE

HTML

<canvas id="demo" width="500" height="400"></canvas> 

的JavaScript

/// get context for canvas, cache dimension 
var ctx = demo.getContext('2d'), 
    w = demo.width, 
    h = demo.height, 

    img = new Image(); /// the image we want to load 

/// when done go draw existing marks and start listening for clicks 
img.onload = function() { 

    renderMarks(); 

    demo.onclick = function(e) { 

     /// convert mouse coord relative to canvas 
     var rect = demo.getBoundingClientRect(), 
      x = e.clientX - rect.left, 
      y = e.clientY - rect.top; 

     /// store mark 
     addMark(x, y); 

     /// redraw everything 
     renderMarks(); 
    } 
} 

這些是主要的功能,該第一呈現在圖像的頂部現有馬克到帆布:

function renderMarks() { 

    /// re-draw image which also serves to clear canvas  
    ctx.drawImage(img, 0, 0, w, h); 

    /// get existing marks from localStorage 
    var marks = localStorage.getItem('marks'), 
     i = 0; 

    /// if any, render them all 
    if (marks !== null) { 

     /// localStorage can only store strings 
     marks = JSON.parse(marks); 

     /// set color and line width of circle 
     ctx.strokeStyle = '#f00'; 
     ctx.lineWidth = 3; 

     /// iterate marks and draw each one 
     for(;i < marks.length; i++) { 
      ctx.beginPath(); 
      ctx.arc(marks[i][0], marks[i][1], 30, 0, 2 * Math.PI); 
      ctx.stroke(); 
     } 
    } 
} 

這增加了一個標記到集合:

function addMark(x, y) { 

    /// get existing marks or initialize 
    var marks = JSON.parse(localStorage.getItem('marks') || '[]'); 

    /// add mark 
    marks.push([x, y]); 

    /// update storage 
    localStorage.setItem('marks', JSON.stringify(marks)); 
} 

(該代碼可以被優化以各種方式,但我做了它表明基本原則)。

如果您現在離開頁面並返回,您會看到標記再次呈現(免責聲明:jsfiddle可能會或不會提供相同的頁面,以便在本地/在「真實」頁面中進行測試以確保)。

這裏的圓圈可以是任何東西,圖像,不同的形狀等等。

要清除標記只需撥打:

localStorage.clear(); 

,或者如果你存儲的其他數據還有:

localStorage.removeItem('marks'); 
+0

真棒,正是我所期待的! – Joelio

0

那麼,你可以爲每個點創建新的圖像,當用戶點擊你用新的圖像替換原始圖像。您可以使用CSS或jQuery來做到這一點)

0

根據您對顯示區域或確切的x/y座標感興趣,可能會使用圖像<map>

還檢查出this stackoverflow問題。

我沒有工作示例可以顯示,但我認爲這符合類似的性質。我不確定你將如何保存調用狀態的信息(返回同一會話或幾天/幾個月後?)。

我希望這有些用處。

相關問題