2013-04-30 56 views
1

我正在繪製塗料應用程序,我試圖將畫布居中在屏幕中間。我做了檢測的任何嘗試都已關閉(仍位於屏幕的左上角),但它在屏幕的中心出現在視覺上。 基本上,當我將它移動到屏幕中心時,它不會畫在畫布上。 任何幫助將不勝感激,謝謝.... 下面我有我的代碼...HTML5畫布(簡單的塗料應用)

+0

您的代碼不在下面。 – 2013-04-30 15:37:14

+0

我不能發佈我的代碼,因爲我的聲望低於10.我可以發佈任何地方,所以你可以看到? – 2013-04-30 15:53:19

+0

[jsfiddle](http://jsfiddle.net/)會比沒有好。 – 2013-04-30 15:54:31

回答

0

這不是從你的問題,你是如何圍繞清楚,但你需要考慮的要素的任何偏移量包含您的canvas當您嘗試將鼠標位置映射到canvas上的位置時。您可以通過在計算時包含包含元素的offsetLeftoffsetTop值(請參見docs)來完成此操作。

如果你抵消div的包裝了canvas位置下面的工作(這我給了一個ID,以方便參考):

function move(e) { 

    // Get the div containing the canvas. Would be more efficient to set this once on document load 
    var container = document.getElementById('container'); 

    if((e.button == 0) && (mouseIsDown)) { 
     g.beginPath(); 
     document.onselectstart = function(){ return false; } 
     //g.fillStyle = "red"; 
     // Account for the offset of the parent when drawing to the canvas 
     g.arc((e.x - container.offsetLeft) - brush, (e.y - container.offsetTop) - brush, brush, 0, Math.PI * 2); 
     g.fill(); 
     g.closePath(); 
    } 
} 

而且一個簡單的演示使用你的小提琴here

+0

謝謝,我改變了div爲525px;頂部:250px;它把它放在中心,這是可以接受的嗎?它的工作原理? – 2013-04-30 16:33:25

+0

不管窗口大小如何,你可能都不想絕對定位它 - 我只是這麼做的,因爲它是生成測試的一種快速方法。我可能會建議使用諸如margin:0 auto之類的東西。但無論哪種方式該方法應該工作。 – 2013-04-30 16:35:47

+0

噢,那好,非常感謝您爲我節省了很多麻煩,我被卡住了一段時間!再次感謝! – 2013-04-30 16:41:06