Senseless
Senseless

Reputation: 99

How can I make a border when filling a randomly sized rectangle with color?

I'm making a very basic paint-program with javascript. I have some drawing tools ready, and a want a black border around the rectangle. The rectangle is filled with a random color. How do I add the border?

I've tried to add two rectangles. And I've tried to use strokeStyle and lineWidth, but no luck so far.

The code for filling the rectangle with a random color works quite well.

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

But when I try to add these lines after context.fillRect...

context.strokeStyle = "#000";
context.lineWidth   = 3;

nothing really happens.

I think maybe the fillStyle and fillRect is hiding the strokeStyle and lineWidth? But I don't how to avoid that from happening?​

Upvotes: 0

Views: 52

Answers (1)

Flash Thunder
Flash Thunder

Reputation: 12036

You need to call strokeRect() after filling:

(...)
context.fillRect(x, y, w, h);
context.strokeStyle = "#000";
context.lineWidth = 3;
context.strokeRect(x, y, w, h);

Upvotes: 1

Related Questions