Canvas fillText and clear
by pedro_g_s
HTML
<body>
<canvas id="myCanvas" width="810" height="512" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<p><strong>Note:</strong> The canvas tag is not supported in Internet Explorer 8 and earlier versions.</p>
</body>
JavaScript
var message = "Hello world";
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.font = "Bold 20px Georgia";
context.textBaseline = "alphabetic";
context.textAlign = "left";
var metrics = context.measureText(message),
textWidth = metrics.width;
var cx = canvas.width / 2,
cy = canvas.height / 2,
tx = textWidth,
ty = 0;
var ctx = context,
x = cx - tx,
y = cy + ty + 0.28 * 20,
w = textWidth,
h = 20 * 1.28,
r = 10,
borderThickness = 5,
borderColor = {
r: 51,
g: 255,
b: 51,
a: 1.0
},
fillColor = {
r: 0,
g: 0,
b: 0,
a: 0.8
};
x -= borderThickness + r;
y += borderThickness + r;
w += borderThickness * 2 + r * 2;
h += borderThickness * 2 + r * 2;
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y - r);
ctx.lineTo(x + w, y - h + r);
ctx.quadraticCurveTo(x + w, y - h, x + w - r, y - h);
ctx.lineTo(x + r, y - h);
ctx.quadraticCurveTo(x, y - h, x, y - h + r);
ctx.lineTo(x, y - r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
ctx.lineWidth = borderThickness;
ctx.fillStyle = "rgba(0,0,0,0.8)";
ctx.fill();
ctx.strokeStyle = "rgba(51,255,51,1.0)";
ctx.stroke();
context.fillStyle = "rgba(255,255,255,1.0)";
context.strokeStyle = "rgba(51,255,51,1.0)";
context.lineWidth = borderThickness;
context.fillText(message, cx - tx, cy + ty);
ctx.fillStyle = "rgba(255,255,255,1.0)";
ctx.fill();
ctx.fillStyle = "rgba(0,0,0,0.8)";
ctx.fill();
context.fillStyle = "rgba(255,0,0,1.0)";
context.fillText("New\ntext",cx-tx,cy+ty);