Filacterial dravinger at Canvas
How to implement comic bubbles.
If Canvas is not supported by the browser, the text is displayed simply without the filacter picture.
Display

Mark Twain.
HTML-code
<div class="bubble">
<canvas id="canvas1" class="bubbleborder" width="240" height="200" >
</canvas>
<div class="bubbletext">
Toutes les généralisations sont fausses, y compris celle-ci. <br><i>Marc Twain.</i>
</div>
</div>
The two layers are located absolutely in the other, both with top = 0 and left = 0, so that they overlap each other.
One is canvas and serves to draw a bubble.
The other is a classic <div> tag and is used to display text. To center the text in the bubble, use the padding property applied to the layer containing it.
Text cannot be formatted directly into canvas.
JavaScript code
function drawBubble(ctx, x, y, w, h, radius)
{
var r = x + w;
var b = y + h;
ctx.beginPath();
ctx.strokeStyle="black";
ctx.lineWidth="2";
ctx.moveTo(x+radius, y);
ctx.lineTo(x+radius/2, y-10);
ctx.lineTo(x+radius * 2, 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();
}
function dispQuote()
{
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
drawBubble(ctx, 10,60,220, 90, 20);
}
window.onload=dispQuote;
We do not use Canvas text functions, which are useless here.
CSS code
.bubble
{
position:relative;
background:green;
float:left; /* because the image at left */
}
.bubbleborder
{
position:absolute;
top:0;
left:0;
}
.bubbletext
{
position:absolute;
top:0;
left:0;
width:220px;
height:200px;
padding:76px 8px 8px 8px;
text-align:center;
}
How to summarize a script
All generalizations are false, but it can be useful to generalize the script to texts of different lengths .
This can be done by adjusting the bubble parameters in JavaScript code to match the length of the text.
- The JavaScript String.length function returns the number of characters. In
- depending on the selected font and character size, the values w (width) and h (height) of the bubble, which are the 4th and 5th arguments of the drawBubble function, will be determined.
Return to Canvas.