gpt4 book ai didi

javascript - 在 HTML 中单击按钮时,JS 变量不会更新

转载 作者:行者123 更新时间:2023-12-02 16:44:06 26 4
gpt4 key购买 nike

我正在网页上制作绘图/ Canvas 应用程序。我想通过按钮更改颜色,但变量没有更新颜色。我调试了代码,发现它确实更新了,但在 Canvas 上绘图时颜色本身没有改变。

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();
};

最佳答案

您需要再次更改变量行程样式

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

关于javascript - 在 HTML 中单击按钮时,JS 变量不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27252269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com