我正在用HTML和JavaScript编写一个简单的绘图工具。
它允许用户通过滑块选择不同大小的刷子。当滑块的值发生变化时,它会更改ctx.lineWidth来实现它。
然而,当ctx.lineWidth发生变化时,旧的笔画也会改变其宽度。我要所有的旧冲程保持他们的大小。有什么解决办法吗?
画布的代码如下:
function brush(){
var el = document.getElementById('canvas');
el.lineJoin = el.lineCap = 'round';
var ctx = el.getContext('2d');
var isDrawing;
el.onmousedown = function(e) {
isDrawing = true;
var bounds = e.target.getBoundingClientRect();
x = e.pageX - bounds.left - scrollX;
y = e.pageY - bounds.top - scrollY;
ctx.moveTo(x, y);
};
el.onmousemove = function(e) {
if (isDrawing) {
console.log(el.lineWidth)
var bounds = e.target.getBoundingClientRect();
x = e.pageX - bounds.left - scrollX;
y = e.pageY - bounds.top - scrollY;
ctx.lineTo(x, y);
ctx.stroke();
}
};
el.onmouseup = function() {
isDrawing = false;
};
}滑块的onchange函数的代码如下:
function adjust_size(){
var value = document.getElementById('slider').value
document.getElementById('canvas').getContext('2d').lineWidth = value
}发布于 2021-01-18 13:35:49
在onmousedown处理程序中,使用ctx.beginPath();启动新路径,
然后在onmouseup处理程序中使用ctx.closePath()关闭它。
例:
el.onmousedown = function(e) {
isDrawing = true;
ctx.beginPath();
var bounds = e.target.getBoundingClientRect();
x = e.pageX - bounds.left - scrollX;
y = e.pageY - bounds.top - scrollY;
ctx.moveTo(x, y);
};
el.onmouseup = function() {
ctx.closePath();
isDrawing = false;
};https://stackoverflow.com/questions/65775178
复制相似问题