2016-01-23 88 views
1

我發現很難讓我的按鈕在HTML畫布內工作。我認爲onclick事件沒有被調用,或者畫布已經過度鋪設,並且繪製了它們,但我無法弄清楚原因。我試圖把一個更高的z-index按鈕這裏展示按鈕無法在HTML畫布上工作

Can I put an HTML button inside the canvas?

但我有沒有用。下面是帆布和按鈕

<canvas id="whiteboard" style="z-index:1; position: absolute; left: 0px; top: 0px;"></canvas> 
<input type="button" style="z-index: 2" value="blue" id="blue" onclick="colorChange('#0000FF');" /> 

這裏的代碼腳本標記

<script src="assets/js/color.js"></script> 

,我試圖在color.js調用

function colorChange(color) { alert("adadadsdasd"); var c = document.getElementById('whiteboard'); var ctx = c.getContext("2d"); ctx.fillStyle = color; }

我的功能對於JS來說是相當新的,所以我很抱歉,如果有任何菜鳥錯誤的話。

+0

你不能改變的了的z-index元素,除非您將位置設置爲至少相對第一位。嘗試添加一個位置:相對;輸入標籤和z-index:2; – magreenberg

回答

1

行爲可以在不同的瀏覽器上有所不同,下面的工作在Firefox和Chrome上(請注意zindex)。小提琴在https://jsfiddle.net/p9gz8rpm/

<canvas id="whiteboard" style="z-index:-1; position: absolute; left: 0px; top: 0px;"></canvas> 

+0

謝謝。然而,將其設置爲這意味着我無法在畫布上繪製,現在按鈕似乎疊加在一起。你可以在div中使用z-index,以便只有該部分位於畫布上方? – Pudding

+0

是的,請使用position:標籤做適當的處理(正如其他答案中所述) – prabindh

0

你忘了補充:

position: absolute; 

你的按鈕。 A z-index僅在具有該集合時纔有效。

<input type="button" style="z-index: 2; position: absolute;" value="blue" id="blue" onclick="colorChange('#0000FF');" /> 

編輯:

如果你不想使用的位置是:絕對的;使用的位置是:相對