2014-12-02 111 views
0

我正在一個網頁上製作一個繪圖/畫布應用程序。我想通過按鈕更改顏色,但變量不更新顏色。我調試了代碼並注意到它會更新,但在畫布上繪製時顏色本身並未改變。當HTML按鈕被點擊時,JS變量不會更新

HTML:

<div id="sketch"> 
    <canvas id="paint"></canvas> 
</div> 

<button onClick="changecolour('blue')">Blue</button> 
<button onClick="test()">DEBUG</button> 

的JavaScript:

var canvas = document.querySelector('#paint'); 
var ctx = canvas.getContext('2d'); 

var sketch = document.querySelector('#sketch'); 
var sketch_style = getComputedStyle(sketch); 
canvas.width = parseInt(sketch_style.getPropertyValue('width')); 
canvas.height = parseInt(sketch_style.getPropertyValue('height')); 

var mouse = {x: 0, y: 0}; 

canvas.addEventListener('mousemove', function(e) { 
    mouse.x = e.pageX - this.offsetLeft; 
    mouse.y = e.pageY - this.offsetTop; 
}, false); 

var colour = "black"; 
function changecolour(choice){ 
    colour = choice;  
} 

function test(click){ 
    alert("You choose " + colour); 
} 

ctx.lineWidth = 5; 
ctx.lineJoin = 'round'; 
ctx.lineCap = 'round'; 
ctx.strokeStyle = colour; 

canvas.addEventListener('mousedown', function(e) { 
    ctx.beginPath(); 
    ctx.moveTo(mouse.x, mouse.y); 

    canvas.addEventListener('mousemove', onPaint, false); 
}, false); 

canvas.addEventListener('mouseup', function() { 
    canvas.removeEventListener('mousemove', onPaint, false); 
}, false); 

var onPaint = function() { 
    ctx.lineTo(mouse.x, mouse.y); 
    ctx.stroke(); 
}; 
+0

你嘗試到最後一段代碼添加到funtion?所以從ctx.lineWidth到var onPaint ....}; ?? – Refilon 2014-12-02 14:55:23

回答

1

您需要再次改變變量strokeStyle

function changecolour(choice){ 
    colour = choice; 
    ctx.strokeStyle = colour; 
} 
+0

它的工作,歡呼! – 2014-12-02 15:00:30

1

您應該影響ctx.strokeStyle本身。當你第一次設置他的值時,color ='black',這意味着你將它設置爲黑色。然後,即使您更改「顏色」值,它也會保持黑色。因此,在這種情況下,你就必須做到這一點:

function changecolour(choice){ 
    ctx.strokeStyle = choice; 
} 

希望幫助

+0

太棒了,謝謝! – 2014-12-02 15:01:24