我正在用 javascript 制作一个非常基本的绘画程序。我准备好了一些绘图工具,并且想要在矩形周围有一个黑色边框。该矩形填充有随机颜色。如何添加边框?
我尝试添加两个矩形。我尝试过使用 strokeStyle 和 lineWidth,但到目前为止还没有成功。
用随机颜色填充矩形的代码效果很好。
tools.rect = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
};
this.mousemove = function (ev) {
if (!tool.started) {
return;
}
var x = Math.min(ev._x, tool.x0),
y = Math.min(ev._y, tool.y0),
w = Math.abs(ev._x - tool.x0),
h = Math.abs(ev._y - tool.y0);
context.clearRect(0, 0, canvas.width, canvas.height);
if (!w || !h) {
return;
}
context.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)';
context.fillRect(x, y, w, h);
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
drawCanvas();
}
};
};
但是当我尝试在 context.fillRect 之后添加这些行时...
context.strokeStyle = "#000";
context.lineWidth = 3;
什么也没发生。
我想也许 fillStyle 和 fillRect 隐藏了 strokeStyle 和 lineWidth?但我不知道如何避免这种情况发生?
最佳答案
填充后需要调用StrokeRect()
:
(...)
context.fillRect(x, y, w, h);
context.strokeStyle = "#000";
context.lineWidth = 3;
context.strokeRect(x, y, w, h);
关于javascript - 用颜色填充随机大小的矩形时如何制作边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55875409/