4

I'm currently trying to create a speechbubble which should be drawn on a canvas element using javascript.

My problem: ctx.fillStyle = "red"; is only changing the ctx.fillText color. But not the background color of the whole path. How could I add a background color to the whole speechbubble?

Jsfiddle: https://jsfiddle.net/dr7q5yay/8/

My current code looks like the following:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");

ctx.font = "15px Helvetica";
var text = 'hello test test';

function drawBubble(ctx, x, y, w, h, radius, text)
{
   var r = x + w;
   var b = y + h;

   ctx.beginPath();
   ctx.fillStyle = "red";
   ctx.fill();
   ctx.strokeStyle = "black";
   ctx.lineWidth = "2";
   ctx.moveTo(x + radius, y);

   ctx.lineTo(r - radius, y);
   ctx.quadraticCurveTo(r, y, r, y + radius);
   ctx.lineTo(r, y + h-radius);
   ctx.quadraticCurveTo(r, b, r - radius, b);
   ctx.lineTo(x + radius, b);
   ctx.quadraticCurveTo(x, b, x, b - radius);
   ctx.lineTo(x, y + radius);
   ctx.quadraticCurveTo(x, y, x + radius, y);
   ctx.stroke();
   ctx.fillText(text, x + 20, y + 30);
}

drawBubble(ctx, 10, 60, ctx.measureText(text).width + 40, 50, 20, text);
d4ne
  • 43
  • 3
  • There is no *background* here. You need to call `ctx.fill()` in order to fill your path. – Kaiido Sep 29 '17 at 01:02
  • ooh shiny, I am developing a game and don't feel like importing yet another sprite just for speechbubbles :3 – Eon Aug 21 '18 at 11:12

1 Answers1

3

The code is almost there, just do a couple of changes in regards to fill() and fillStyle:

diagram, experimental

Modified fiddle

You can btw use arc()s to draw a rounded rectangles as well (slightly less overhead).