ValarDohaeris
ValarDohaeris

Reputation: 649

unable to draw rectangle on canvas

I am drawing an image on a canvas with white background color. I want to draw a border on the image and I am unable to do so. Here is my code:

var canvas = parent.document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.fillStyle = "black";
context.font = "50px Arial";
//context.fillText(chartId, canvas.width-200, 50);
context.drawImage(image, 0, 0);
context.fillStyle = "#000000";
context.rect(0,0,canvas.width,canvas.height);
context.globalCompositeOperation = "destination-over";
context.fillStyle = "#FFFFFF";

But I don't see any border when I download this image.

Upvotes: 2

Views: 204

Answers (3)

LIXer
LIXer

Reputation: 362

it looks like,you don't do the context.stroke() operation?

Upvotes: 0

Niddro
Niddro

Reputation: 1725

There are two things missing.

  1. is the context.stroke(); after painting your rect.
  2. You should start drawing your rect() with context.beginPath();. This is to avoid the next stroke to also affect the first rectangle that you drew.

Another possible solution is to instead use the function context.strokeRect(); saving you the trouble of having to beingPath() and stroke().

    canvas.width = image.width;
    canvas.height = image.height;
    var context = canvas.getContext('2d');
    context.fillStyle = "black";
    context.font = "50px Arial";
    //context.fillText(chartId, canvas.width-200, 50);
    context.drawImage(image, 0, 0);
    context.fillStyle = "#000000";
    context.beginPath();
    context.rect(0,0,canvas.width,canvas.height);
    context.stroke();
    context.globalCompositeOperation = "destination-over";
    context.fillStyle = "#FFFFFF";

Upvotes: 2

Sebastian Nette
Sebastian Nette

Reputation: 7812

You forgot to stroke your rect.

context.stroke();

Upvotes: 2

Related Questions