I am drawing five horizontal lines to an HMTL 5 2D canvas:
var canvas_ctx = my_canvas.getContext("2d");
canvas_ctx.lineWidth = 0.5;
canvas_ctx.strokeStyle = "black";
{
let line_x = 0;
let line_length = canvas_ctx.width;
let offset = 5;
let numLines = 5;
let numYincrement = 10;
for (let i=0;i<numLines * numYincrement;i+=numYincrement) {
//canvas_ctx.beginPath();
canvas_ctx.moveTo(line_x,i + offset);
canvas_ctx.lineTo(line_length,i + offset);
canvas_ctx.stroke();
//canvas_ctx.closePath();
}
}
This should, ideally result in 5 black lines. Instead, the color of the lines seems to fade with each new line (as if it's a gradient!), so that line 5 is gray. If I uncomment canvas_ctx.beginPath(); and canvas_ctx.closePath();, all lines become gray. Why is this happening??
Strokes do overlap from both sides of the coordinates.
var ctx = c.getContext('2d');
ctx.strokeStyle="red";
// draw big
ctx.scale(30, 30);
ctx.beginPath();
ctx.moveTo(5, 0);
ctx.lineTo(5, 10);
ctx.stroke();
drawPixelGrid();
function drawPixelGrid() {
// simply renders where the pixel bounds are
ctx.beginPath();
// remove the zoom
ctx.setTransform(1,0,0,1,0,0);
ctx.strokeStyle = 'gray';
ctx.lineWidth = 2; // avoid the problem we are demonstrating by using a perfect lineWidth ;-)
for(let y=0; y<=300; y+=30) {
ctx.moveTo(0, y);
ctx.lineTo(300, y);
for(let x=0; x<=300; x+=30) {
ctx.moveTo(x, 0);
ctx.lineTo(x, 300);
}
}
ctx.stroke();
}
<canvas id="c" height=300></canvas>
But obviously, a pixel can't be set to two colors at the same time. So browsers apply antialiasing, which will fade your pixel color to an other color, being the result of mixing the background and the foreground color.
So for a black stroke over a white or transparent background, this leads to actual gray pixels being rendered. Here I'll keep using red as an example:
var ctx = c.getContext('2d');
ctx.strokeStyle="red";
// first draw as on a 10*10 canvas
ctx.beginPath();
ctx.moveTo(5, 0);
ctx.lineTo(5, 10);
ctx.stroke();
// zoom it
ctx.imageSmoothingEnabled = 0;
ctx.globalCompositeOperation = 'copy';
ctx.drawImage(c, 0,0,9000,9000);
drawPixelGrid();
// this is not red...
function drawPixelGrid() {
ctx.globalCompositeOperation = 'source-over';
ctx.beginPath();
ctx.setTransform(1,0,0,1,0,0);
ctx.strokeStyle = 'gray';
ctx.lineWidth = 2;
for(let y=0; y<=300; y+=30) {
ctx.moveTo(0, y);
ctx.lineTo(300, y);
for(let x=0; x<=300; x+=30) {
ctx.moveTo(x, 0);
ctx.lineTo(x, 300);
}
}
ctx.stroke();
}
<canvas id="c" height=300></canvas>
One way to avoid it is generally to apply an offset on your coordinates so that the line extends correctly on pixels boundaries. E.g for a 1px lineWidth, you would apply a 0.5 offset:
var ctx = c.getContext('2d');
ctx.strokeStyle="red";
// first draw as on a 10*10 canvas
ctx.beginPath();
ctx.moveTo(5.5, 0); // offset +0.5px
ctx.lineTo(5.5, 10);
ctx.stroke();
// zoom it
ctx.imageSmoothingEnabled = 0;
ctx.globalCompositeOperation = 'copy';
ctx.drawImage(c, 0,0,9000,9000);
drawPixelGrid();
// now we've got a real red
function drawPixelGrid() {
ctx.globalCompositeOperation = 'source-over';
ctx.beginPath();
ctx.setTransform(1,0,0,1,0,0);
ctx.strokeStyle = 'gray';
ctx.lineWidth = 2;
for(let y=0; y<=300; y+=30) {
ctx.moveTo(0, y);
ctx.lineTo(300, y);
for(let x=0; x<=300; x+=30) {
ctx.moveTo(x, 0);
ctx.lineTo(x, 300);
}
}
ctx.stroke();
}
<canvas id="c" height=300></canvas>
But in your case, you are drawing at 0.5px lineWidth, so no offset will be able to get rid of this antialiasing.
So if you want perfect color, choose a correct lineWidth.
Related
I want to transform the head of a dog to turn, but I don't know how to select an entire function and not more and transform this into an animation.
// The function
Head();
rotate();
// this is for the entire canvas, but how to do it specifically for a function
context.rotate(rotation);
rotation += 0.04
I am also not very familiar with animating in html canvas
You need to save() the context before the transformation. Next you call the function that draw the head. Then you restore() the context. In this way the head will be transformed nut not the rest of the canvas.
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = 300,
cx = cw / 2;
let ch = canvas.height = 300,
cy = ch / 2;
let rotation = 0
function background(){
ctx.beginPath();
ctx.fillStyle="gold";
ctx.fillRect(20,20,160,50);
ctx.beginPath();
ctx.fillStyle="gold";
ctx.fillRect(120,220,160,50);
}
function Head(){
ctx.fillStyle = "skyBlue";
ctx.beginPath();
ctx.arc(0,0,40,0,2*Math.PI);
ctx.fill();
ctx.beginPath();
ctx.arc(-15,-5,8,0,2*Math.PI);
ctx.fillStyle="white";
ctx.fill();
ctx.beginPath();
ctx.arc(15,-5,8,0,2*Math.PI);
ctx.fillStyle="white";
ctx.fill();
ctx.beginPath();
ctx.arc(0,0,30,Math.PI/10,9*Math.PI/10);
ctx.strokeStyle="white";
ctx.stroke();
}
function frame(){
requestAnimationFrame(frame);
rotation += 0.04;
ctx.clearRect(-cw,-ch,2*cw,2*ch);
background()
ctx.save();
ctx.translate(cx,cy);
ctx.rotate(rotation);
// The function
Head();
ctx.restore();
}
frame()
canvas{border:1px solid}
<canvas id="canvas"></canvas>
I am trying to using context.clip() to clip a draw arc from other one and fill the clipped result.
But when i clip section & fill it, it gives pixelated fill .
var ctx = document.getElementById("canvas").getContext("2d");
var x = 150 ;
var y = 150 ;
var r = 100 ;
ctx.save() ;
ctx.translate(x,y) ;
ctx.beginPath() ;
ctx.arc(0,0,r,0,2*Math.PI);
ctx.closePath() ;
ctx.fillStyle = "cyan" ;
ctx.fill() ;
ctx.lineWidth = 10;
ctx.stroke();
ctx.restore() ;
ctx.save() ;
ctx.clip() ;
ctx.translate(x,y);
ctx.beginPath();
ctx.moveTo(r,-r-10);
ctx.arc(0,-r-10,r,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle = "#f2f2f2";
ctx.fill();
ctx.lineWidth = 1;
ctx.stroke();
ctx.restore();
https://jsfiddle.net/x0d0n40z/1/
An alternative approach which eliminates the need for clip()/save()/restore() is to use a few steps of compositing.
Clipping mask is anti-aliased in some browsers while in other not. To obtain consistency (and in some cases also performance since save-clip-restore are relative expensive operations) using composition is preferred if possible.
In this case:
Fill main arc in target color
Define a clipping arc
Change composite mode to destination-out and fill (will cut main)
Change composite mode to source-atop and stroke (will outline cut)
Change composite mode to source-over and stroke outline of main circle
Example
Update: Simplified steps (with the last step merged into the process, ref. comments). I also chose to demonstrate use of the Path2D since we can reuse the object without interfering with the path on the ordinary context -
var ctx = c.getContext("2d"),
p = new Path2D(), // this will store main shape for reuse
x = 75, y = 75, radius = 70;
// main arc
p.arc(x, y, radius, 0, 6.28); // store to path object
ctx.fillStyle = "cyan";
ctx.fill(p); // fill path object
// clip top arc
ctx.globalCompositeOperation = "source-atop";
ctx.arc(x, y - radius, radius, 0, 6.28);
ctx.fillStyle = "#09f";
ctx.fill();
ctx.lineWidth = 5;
ctx.stroke();
// stroke main arc
ctx.globalCompositeOperation = "source-over";
ctx.stroke(p); // stroke path object
body {background:#e9e9e9}
<canvas id=c></canvas>
Old version:
var ctx = c.getContext("2d"),
x = 75, y = 75, radius = 70;
// main arc
ctx.arc(x, y, radius, 0, 6.28);
ctx.fillStyle = "cyan";
ctx.fill();
// clipping arc
ctx.beginPath();
ctx.arc(x, y - radius, radius, 0, 6.28);
// cut step
ctx.globalCompositeOperation = "destination-out";
ctx.fill();
// stroke gap step
ctx.globalCompositeOperation = "source-atop";
ctx.lineWidth = 10;
ctx.stroke();
// stroke whole outline
ctx.globalCompositeOperation = "source-over";
ctx.beginPath();
ctx.arc(x, y, radius, 0, 6.28);
ctx.lineWidth = 5;
ctx.stroke();
// if you want to color the clip then use this:
ctx.globalCompositeOperation = "destination-atop";
ctx.fillStyle = "#09f";
ctx.fill();
body {background:#e9e9e9}
<canvas id=c></canvas>
The problem is that the clip boundary is not being anti alised.
To solve you can render the shape without using the clip. The ctx.arc method lets you set the start and end angles so you can get the inset by filling two arcs.
You will need to get the angles where the clip circle and the inset circle intercept.
For this case it is very simple. First get the distance between the circles, and the angle from one to the other. This works only for two circles of same radius.
var c = {x:?,y:?}; // circle one location
var c1 = {x:?,y:?}; // circle two location
var radius = ?; // radius of both
var angle = Math.atan2(c1.y - c.y, c1.x - c.x); // get the angle from one to the next
var dist = Math.hypot(c1.x - c.x, c1.y - c.y); // get the distance. NOTE IE does not have hypot so do it the normal way with Math.sqrt....
Now you have the angle and distance the intercepts are a simple relationship between the distance and the radius
var iAngle = Math.acos(dist / 2 / radius); // the angle from the line between the circles
// to the intercepts
Now you have that angle you can draw the two arcs
ctx.beginPath();
ctx.arc(c.x,c.y,radius,angle - iAngle , angle + iAngle); // first arc
ctx.arc(c1.x,c1.y, radius, angle + Math.PI - iAngle, angle + Math.PI + iAngle); // second arc
ctx.fill();
ctx.stroke();
There is not much you can do to prevent the jaggies from effecting the clip area. Another way to achieve clipping is to use ctx.globalCompositeOperation to render a mask. You can mask in and out, and many more options. This will be a better solution when the clipping area becomes more complex.
I finally figured the right way to correct the bug .
Heres the clean result of what i wanted https://jsfiddle.net/x0d0n40z/6/
Code :
var ctx = document.getElementById("canvas").getContext("2d");
var r = 50
x = ctx.canvas.width/2;
y = ctx.canvas.height/2;
var offset = 60;
ctx.save();
ctx.setTransform(1,0,0,1.5,x,y);
ctx.beginPath();
ctx.arc(0,0,r,0,2*Math.PI);
ctx.stroke();
ctx.clip();
ctx.beginPath();
ctx.arc(0,0,r,0,2*Math.PI,false);
ctx.fillStyle = "cyan";
ctx.fill();
ctx.setTransform(1, 0, 0, 1, x, y);
ctx.beginPath();
ctx.arc(0,-offset,r,0,2*Math.PI,false);
ctx.fillStyle = "#f2f2f2";
ctx.fill();
ctx.lineWidth = 1 ;
ctx.stroke();
ctx.setTransform(1,0,0,1.5,x,y);
ctx.beginPath();
ctx.arc(0,0,r,0,2*Math.PI,false);
ctx.lineWidth = 3 ;
ctx.stroke();
ctx.restore();
Source from were i learned to use clip : http://www.html5canvastutorials.com/advanced/html5-canvas-clipping-region-tutorial/
I'm trying to draw several shapes to a canvas and I'm running into a strange issue. When I try to draw a white rectangle on the canvas before drawing my shape, the shape never shows up. What am I doing wrong?
Sample code:
// drawing a white background
// This breaks it. If I comment thiese two line out, it works.
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, Canvas.width, Canvas.height);
// Draw the rectangle
ctx.lineWidth = LineWidth;
ctx.strokeStyle = Color;
ctx.beginPath();
var startPos = Ordinates[0];
ctx.moveTo(startPos.start.x, startPos.start.y);
ctx.lineTo(startPos.stop.x, startPos.stop.y);
for(var i = 0; i < Ordinates.length; i++){
if(i === 0) continue;
ctx.lineTo(Ordinates[i].stop.x, Ordinates[i].stop.y);
}
ctx.closePath();
ctx.fill();
And here's a fiddle.
If you comment out the 2 lines that draws the white background rectangle, it works fine. What am I doing wrong?
ctx.fillStyle = "#FFFFFF"; // <-- set the fill color to white
ctx.fillRect(0, 0, Canvas.width, Canvas.height);
// Draw the rectangle
ctx.lineWidth = LineWidth;
ctx.strokeStyle = Color;
ctx.beginPath();
var startPos = Ordinates[0];
ctx.moveTo(startPos.start.x, startPos.start.y);
ctx.lineTo(startPos.stop.x, startPos.stop.y);
for(var i = 0; i < Ordinates.length; i++){
if(i === 0) continue;
ctx.lineTo(Ordinates[i].stop.x, Ordinates[i].stop.y);
}
ctx.closePath();
ctx.fill(); // <--- filling with white, while the background is still. you can remove this line btw
ctx.fillStyle = '#000000'; // <-- now we set it to black
ctx.fill(); // <--- filling with black now
also, if you want to see an outline of the path:
ctx.stroke();
this draws the outline of it in the right color.
But in a reply to v.rouge you just said you wanted it white with a black outline:
ctx.fillStyle = '#ffffff';
ctx.strokeStyle = '#000000';
ctx.fill();
ctx.stroke();
done :-)
Fillstyle is white. Drawing is white. Might explain.
I was surprised to find out that apparently the canvas API does not allow you to apply gradients to shadows like this:
var grad = ctx.createLinearGradient(fromX, fromY, toX, toY);
grad.addColorStop(0, "red");
grad.addColorStop(1, "blue");
ctx.strokeStyle = grad;
ctx.lineWidth = 3;
ctx.shadowBlur = 10;
ctx.shadowColor = grad; // doesn't seem to work
ctx.beginPath();
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
ctx.closePath();
ctx.stroke();
// linear gradient from start to end of line
var canvas = document.getElementById('mycanvas'),
ctx = canvas.getContext('2d'),
fromX = 3,
fromY = 3,
toX = 197,
toY = 197,
grad = ctx.createLinearGradient(fromX, fromY, toX, toY);
canvas.width = 200;
canvas.height = 200;
grad.addColorStop(0, "red");
grad.addColorStop(1, "blue");
ctx.strokeStyle = grad;
ctx.lineWidth = 3;
ctx.shadowBlur = 20;
ctx.shadowColor = grad;
ctx.beginPath();
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
ctx.closePath();
ctx.stroke();
body {
background: black
}
<canvas id="mycanvas"></canvas>
One workaround is to simply draw the line/shape/etc. multiple times at different sizes and opacity to get a similar result:
var grad = ctx.createLinearGradient(fromX, fromY, toX, toY);
canvas.width = 200;
canvas.height = 200;
grad.addColorStop(0, "red");
grad.addColorStop(1, "blue");
ctx.strokeStyle = grad;
ctx.lineWidth = 3;
//ctx.shadowBlur = 20;
//ctx.shadowColor = grad;
for (var i = 10; i > 1; i--) {
ctx.lineWidth = i;
ctx.globalAlpha = 1 / i;
ctx.beginPath();
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
ctx.closePath();
ctx.stroke();
}
// linear gradient from start to end of line
var canvas = document.getElementById('mycanvas'),
ctx = canvas.getContext('2d'),
fromX = 3,
fromY = 3,
toX = 197,
toY = 197,
grad = ctx.createLinearGradient(fromX, fromY, toX, toY);
canvas.width = 200;
canvas.height = 200;
grad.addColorStop(0, "red");
grad.addColorStop(1, "blue");
ctx.strokeStyle = grad;
ctx.lineWidth = 3;
//ctx.shadowBlur = 20;
//ctx.shadowColor = grad;
for (var i = 10; i > 1; i--) {
ctx.lineWidth = i;
ctx.globalAlpha = 1 / i;
ctx.beginPath();
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
ctx.closePath();
ctx.stroke();
}
body {
background: black;
}
<canvas id="mycanvas"></canvas>
Here's the comparison. Although the change is subtle, the right image shows roughly the desired effect.
Is there a better way of doing this? I imagine there's a more efficient way than drawing the same thing multiple times. Does anyone know of a library that provides this kind of functionality?
Use the filter property of the canvas 2d context. MDN filter though (as usual) it does say filter is not supported on Chrome it has been from some time on the Beta version. For IE I do not know and for FF it has been supported for some time. You will have to test for it if you use it.
UPDATE
Support does not seam to be automatic. Though MDN shows support for Firefox you must set the canvas.filters.enable to true (whatever that means, I am sure firefox lovers know) and seams for chrome you must go to chrome://flags then set experimental canvas features to enabled
More
I have added a fallback as there is such limited support. It uses a second canvas to blur the shadow by using the ctx.imageSmoothingEnabled=true; and rendering at a scale one half the blur amount. So if blur is 5 pixels then in background canvas must be one tenth the size. Then on the original canvas render the background canvas at full size with smoothing on.
No the best result and will no be good for lines, but its fast and can be played around with to optimise results.
Snippet to show how to detect support and use.
var canvas = document.getElementById("canV");
var ctx = canvas.getContext("2d");
var g = ctx.createLinearGradient(10,10,100,100);
for(var i = 0; i <= 1; i+= 0.05){
g.addColorStop(i,"hsl("+Math.floor(i*360)+",100%,50%)");
}
var gDark = ctx.createLinearGradient(20,20,100,100);
for(var i = 0; i <= 1; i+= 0.05){
gDark.addColorStop(i,"hsl("+Math.floor(i*360)+",100%,30%)");
}
ctx.font = "16px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "hanging";
if(ctx.filter !== undefined){
ctx.fillText("Using filter.",65,125);
ctx.fillStyle = gDark;
ctx.filter = "blur(5px)"; // set the blur
ctx.fillRect(20,20,100,100); // draw the shadow
ctx.fillStyle = g; // set the lighter gradoent
ctx.filter = "blur(0px)"; // remove the blur
ctx.lineWidth = 2;
ctx.strokeStyle = "black"
ctx.fillRect(10,10,100,100); // draw the box
ctx.strokeRect(10,10,100,100); // with line to look nice.
}else{
// fallback method
ctx.fillText("Using Fallback.",60,125);
var can = document.createElement("canvas"); // create a second canvas
can.width = Math.floor(canvas.width/10); // size to make one pixel the
can.height =Math.floor(canvas.height/10); // size of the blur
var ctxS = can.getContext("2d");
ctxS.setTransform(1/10,0,0,1/10,0,0); // set scale so can work in same coords
ctxS.fillStyle = gDark;
ctxS.fillRect(20,20,100,100); // draw the shadow
ctx.imageSmoothingEnabled=true;
ctx.drawImage(can,0,0,canvas.width,canvas.height);
}
ctx.fillStyle = g; // set the lighter gradoent
ctx.lineWidth = 2;
ctx.strokeStyle = "black"
ctx.fillRect(10,10,100,100); // draw the box
ctx.strokeRect(10,10,100,100); // with line to look nice.
#canV {
width:200px;
height:200px;
}
<canvas id="canV" width = 200 height =200></canvas>
I'm currently using HTML5's canvas to render a number of strings using the fillText method. This works fine, but I'd also like to give each string a 1px black outer stroke. Unfortunately the strokeText function seems to apply an inner stroke. To counter this, I've written a drawStrokedText function that achieves the effect I'm after. Unfortunately it's horrible slow (for obvious reasons).
Is there a fast, cross-browser way of achieving a 1px outer stroke using native canvas functionality?
drawStrokedText = function(context, text, x, y)
{
context.fillStyle = "rgb(0,0,0)";
context.fillText(text, x-1, y-1);
context.fillText(text, x+1, y-1);
context.fillText(text, x-1, y);
context.fillText(text, x+1, y);
context.fillText(text, x-1, y+1);
context.fillText(text, x+1, y+1);
context.fillStyle = "rgb(255,255,255)";
context.fillText(text, x, y);
};
Here's an example of the effect at work:
What's wrong with stroke? Since half the stroke will be outside of the shape, you can always draw the stroke first with a line width of double what you want. So if you wanted a 4px outer stroke you could do:
function drawStroked(text, x, y) {
ctx.font = '80px Sans-serif';
ctx.strokeStyle = 'black';
ctx.lineWidth = 8;
ctx.strokeText(text, x, y);
ctx.fillStyle = 'white';
ctx.fillText(text, x, y);
}
drawStroked("37°", 50, 150);
Which makes:
live fiddle here: http://jsfiddle.net/vNWn6/
IF that happens to not look as accurate at smaller text rendering scales, you can always draw it large but scale it down (in the above case you'd do ctx.scale(0.25, 0.25))
Simon's answer is a good solution, yet it may have mitering glitches in some cases, especially with capital 'M', 'V', & 'W':
drawStroked("MVW", 50, 150);
http://jsfiddle.net/hwG42/1/
In this case, it's best to utilize:
ctx.miterLimit=2;
http://jsfiddle.net/hwG42/3/
Best of luck!
The above answers are great, using some of these solutions* and some of my own ideas, I made a quick reference and some creative alternatives in the below fiddle.
*All credits given where due in the fiddle code
drawStrokedText ( text, x, y );
drawShadowedText ( text, x, y, shadowBlur);
drawGlowingText ( text, x, y, glowColorHex, glowDistance);
drawBlurredText ( text, x, y, blurAmount);
drawReflectedText ( text, x, y, reflectionScale, reflectionOpacity);
https://jsfiddle.net/vtmnyea8/
// Author: Aaron Edmistone
// Text effects using HTML5 Canvas with 2D Context.
// https://stackoverflow.com/questions/7814398/a-glow-effect-on-html5-canvas
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// prepare the presentation of the canvas
ctx.fillStyle = 'black';
ctx.fillRect(0,0,250,450);
ctx.fillStyle = 'gray';
ctx.fillRect(250,0,250,450);
ctx.fillStyle = 'white';
ctx.fillRect(500,0,250,450);
ctx.fillStyle = '#0066CC';
ctx.fillRect(750,0,250,450);
// prepare the font and fill
ctx.font = "80px Sans-serif";
ctx.fillStyle = "white";
function drawStrokedText(text, x, y)
{
// using the solutions from #Simon Sarris and #Jackalope from
// https://stackoverflow.com/questions/7814398/a-glow-effect-on-html5-canvas
ctx.save();
ctx.strokeStyle = 'black';
ctx.lineWidth = 8;
ctx.lineJoin="round";
ctx.miterLimit=2;
ctx.strokeText(text, x, y);
ctx.fillText(text, x, y);
ctx.restore();
}
function drawShadowedText(text, x, y, shadowBlur = 3)
{
ctx.save();
ctx.shadowBlur = shadowBlur;
ctx.shadowColor = "#000000";
ctx.shadowOffsetX = 4;
ctx.shadowOffsetY = 4;
ctx.fillText(text, x, y);
ctx.restore();
}
function drawGlowingText(text, x, y, glowColorHexString, glowDistance = 10)
{
ctx.save();
ctx.shadowBlur = glowDistance;
ctx.shadowColor = glowColorHexString;
ctx.strokeText(text, x, y);
for(let i = 0; i < 3; i++)
ctx.fillText(text, x, y); //seems to be washed out without 3 fills
ctx.restore();
}
function drawBlurredText(text, x, y, blur = 5)
{
//using technique from https://www.html5rocks.com/en/tutorials/canvas/texteffects/
ctx.save();
let width = ctx.measureText(text).width + blur * 2;
ctx.shadowColor = ctx.fillStyle;
ctx.shadowOffsetX = width + x + ctx.canvas.width;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = blur;
ctx.fillText(text, -width + -ctx.canvas.width, y);
ctx.restore();
}
function drawReflectedText(text, x, y, reflectionScale = 0.2, reflectionAlpha = 0.10)
{
ctx.save();
ctx.fillText(text, x, y);
ctx.scale(1, -reflectionScale);
ctx.globalAlpha = reflectionAlpha;
ctx.shadowColor = ctx.fillStyle;
ctx.shadowBlur = 15;
ctx.fillText(text, x, -(y * (1 / reflectionScale)));
ctx.restore();
}
for(let i = 0; i < 4; i++)
{
drawStrokedText ("MVW", 20 + i * 250, 80 * 1);
drawShadowedText ("MVW", 20 + i * 250, 80 * 2, 3);
drawGlowingText ("MVW", 20 + i * 250, 80 * 3, "#FF0000", 10);
drawBlurredText ("MVW", 20 + i * 250, 80 * 4, 5);
drawReflectedText ("MVW", 20 + i * 250, 80 * 5, 0.5, 0.5);
}
<canvas id="myCanvas" width="1000" height="500"></canvas>
Output of the fiddle:
What it supports:
Outline text
Shadow text
Glowing text
Blurred text
Reflected text
Some performance metrics:
Considering using this in a game or at high frame rates?
Check out this jsperf using the above methods.
https://jsperf.com/various-text-effects-html5-2d-context
For a smooth shadow you can try this
ctx.beginPath();
ctx.fillStyle = 'white';
ctx.font = "bold 9pt Tahoma";
ctx.shadowBlur = 3;
ctx.textAlign = "center";
ctx.shadowColor = "#000000";
ctx.shadowOffs = 0;
ctx.fillText('www.ifnotpics.com', 100, 50);
ctx.closePath();