我正在网页上制作绘图/画布应用程序。我想通过按钮更改颜色,但变量不会更新颜色。我调试了代码,发现它确实更新了,但在画布上绘图时颜色本身没有改变。
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 :(得分:1)
您需要再次更改变量strokeStyle
。
function changecolour(choice){
colour = choice;
ctx.strokeStyle = colour;
}
答案 1 :(得分:1)
您应该影响ctx.strokeStyle本身。当您第一次设置其值时,color ='black',这意味着您将其设置为黑色。即使您更改“颜色”值,它也会保持黑色。所以在这种情况下,你只需要这样做:
function changecolour(choice){
ctx.strokeStyle = choice;
}
希望有所帮助