2012-03-20 182 views
1

所以我希望能夠吸引到這個畫布上我創建,讓我告訴你我的Javascript代碼,我會解釋發生了什麼:繪製在畫布上

我有兩個畫布,一個具有正方形50X50總是跟着鼠標,另一個我想用來畫畫。到目前爲止,這工作,但我希望能夠拖動鼠標,並繼續繪製,而不是每次我想畫的時候點擊鼠標。

function start(){ 
var canvas_hover_tmp = document.getElementById('canvas_hover'); 
canvas_hover = canvas_hover_tmp.getContext('2d'); 
var canvas_click_tmp = document.getElementById('canvas_draw'); 
canvas_click = canvas_click_tmp.getContext('2d'); 

window.addEventListener('mousemove', moved, false); //move square with mouse on mouse move 
window.addEventListener('mousedown', draw, false); //draw square to canvas at specific location from where mouse is 
} 

此功能只是讓畫布的我想使用,並設置它們,然後調用事件偵聽器,一個跟隨鼠標和一個點擊並拖動,繪製

function moved(pos){ 
canvas_hover.clearRect(0,0,1000,600); 
var x = pos.clientX; 
var y = pos.clientY; 
canvas_hover.fillRect(x-25, y-25,50,50);  
} 

這功能讓我懸停一個盒子,用鼠標

function draw(draw_pos){ 
var x = draw_pos.clientX; 
var y = draw_pos.clientY; 
canvas_click.fillRect(x-25,y-25,50,50); 
} 

這是根據鼠標的位置在特定位置畫在畫布上的功能徘徊,我可以點擊,它會繪製一個正方形,但我不能點擊並拖動並繼續繪製,如我所願。我怎樣才能做到這一點?

window.addEventListener('load', drawRect, false); //call first function start 

我已經嘗試設置一個名爲draw = 1變量,當它等於一,這意味着繼續繪製和0時停止。但是我把它放在while循環中,發生的一切就是頁面崩潰。

我有這兩個畫布的CSS3設置爲相互覆蓋。

很抱歉,如果這是令人困惑,我不知道這

任何幫助將如何字是真棒,

謝謝:)

回答

1

你的「設置變量」的做法是正確的。你想,只要鼠標按鈕是堅持畫畫,所以你要聽上mousedownmousemovemouseup並介紹一些全局變量(比如drawOnSecond爲「借鑑第二層」):

//move square with mouse on mouse move 
window.addEventListener('mousemove', moved, false); 

//draw square to canvas at specific location from where mouse is 
//you shouldn't drop this listener, as this would prevent drawing via clicking 
window.addEventListener('mousedown', draw, false); 

// enable/disable drawing while moving the mouse 
window.addEventListener('mousedown', enableDraw, false); 
window.addEventListener('mouseup', disableDraw, false); // disable 

然後你必須調整moved功能一點點,實現enableDraw/disableDraw:

function moved(pos){  
    canvas_hover.clearRect(0,0,1000,600); 
    var x = pos.clientX; 
    var y = pos.clientY; 
    canvas_hover.fillRect(x-25, y-25,50,50); 
    if(drawOnSecond) // <<---- global variable, default false 
     draw(pos); 
} 

function enableDraw(){ 
    drawOnSecond = true; 
} 

function disableDraw(){ 
    drawOnSecond = false; 
} 

JSFiddle

+0

的作品就像一個魅力現在,謝謝! – Jacob 2012-03-20 07:11:50