Strange Font Behaviour On HTML Canvas - javascript

I have this code to draw some text on my HTML Canvas :
$("#canvastext").keyup(function(){
ctx.lineWidth = 8;
ctx.font = '20pt Arial';
ctx.strokeStyle = 'black';
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
var text = document.getElementById('canvastext').value;
text = text.toUpperCase();
x = canvas.width/2;
y = canvas.height - canvas.height/4.5;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeText(text, x, y);
ctx.fillText(text, x, y);
});
But why some characters have this strange shape :
Why A, M, V, W have ugly stroke lines?

It's because the linejoin property in canvas is default to miter, and when the line join angle is smaller, it'll create a sharper join at the point, which will extend longer.
Solution:
Set ctx.miterLimit, like ctx.miterLimit=1.
Use other lineJoin value, like round, `
var canvas = document.getElementById('cv');
var canvas2 = document.getElementById('cv2');
var ctx = canvas.getContext('2d');
var ctx2 = canvas2.getContext('2d');
$("#canvastext").keyup(function(){
ctx.lineWidth = 8;
ctx.font = '20pt Arial';
ctx.strokeStyle = 'black';
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.miterLimit = 2;
ctx2.lineWidth = 8;
ctx2.font = '20pt Arial';
ctx2.strokeStyle = 'black';
ctx2.fillStyle = 'white';
ctx2.textAlign = 'center';
ctx2.lineJoin = 'round';
var text = document.getElementById('canvastext').value;
text = text.toUpperCase();
x = canvas.width/2;
y = canvas.height - canvas.height/4.5;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeText(text, x, y);
ctx.fillText(text, x, y);
x = canvas2.width/2;
y = canvas2.height - canvas.height/4.5;
ctx2.clearRect(0, 0, canvas.width, canvas.height);
ctx2.strokeText(text, x, y);
ctx2.fillText(text, x, y);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="canvastext"/><br/>
<canvas id="cv" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<canvas id="cv2" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

Use shadow*, instead of stroke*:
ctx.textBaseline = “top”
ctx.shadowColor = “#000”
ctx.shadowOffsetX = width;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = blur;
ctx.fillText(text, -width, 0);

Related

How to remove shadow from text in circle?

In the graphic the idea was to put a shadow only on the white circle, but it looks like the shadow effect was applied to the text, which shouldn't happen.
Canvas:
<canvas class="gradient" id="canvas_gradient_chart" height="70"></canvas>
Javascript:
drawChartGradient(canvas, radian, height, metric) {
const rect = canvas.getBoundingClientRect();
const ctx = canvas.getContext("2d");
canvas.width = rect.width;
canvas.height = height;
ctx.beginPath();
const centerY = canvas.height / 2;
const centerX = this.positionXChart(canvas.width, metric, 20);
ctx.arc(centerX, centerY, radian, 0, Math.PI * 2, false);
ctx.fillStyle ="#ffffff";
ctx.filter = 'drop-shadow(2px 2px 5px rgba(0,0,0,0.6))';
ctx.fill();
ctx.font = 'bold 14pt sans-serif';
ctx.textAlign = 'center';
ctx.strokeStyle ='#ffffff'
ctx.stroke();
ctx.fillStyle ="#622BCF"; // <-- Text colour here
ctx.shadowBlur=0;
ctx.shadowColor='transparent';
ctx.fillText(`${metric ? metric : 0}`, centerX, centerY+8);
//ctx.globalCompositeOperation = 'destination-over';
ctx.globalCompositeOperation = 'source-over';
canvas.addEventListener('mousemove', (e) => {
const relativeCoodinates = {
x:parseInt(`${centerX}`),
y:parseInt(`${centerY}`),
r:radian
}
});
ctx.globalCompositeOperation = 'destination-over';
ctx.save();
ctx.restore();
}
positionXChart(size, number, distance) {
return size/(200 + distance) * (parseInt(`${number}`) + 100 + distance / 2);
}
Canvas would render:
You have to reset the filter or the same will be applied to all elements:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter#value
See working sample:
const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")
ctx.beginPath()
ctx.arc(50, 50, 40, 0, Math.PI * 2)
ctx.fillStyle = "#ffffff"
ctx.filter = 'drop-shadow(2px 2px 5px)'
ctx.fill()
ctx.beginPath()
ctx.font = 'bold 30pt sans-serif'
ctx.textAlign = 'center'
ctx.textBaseline = "middle"
ctx.fillStyle = "#622BCF" // <-- Text colour here
ctx.filter = 'none'
ctx.fillText("80", 50, 50)
<canvas id="canvas" ></canvas>
And the textBaseline = "middle" I think does a good job at keeping the text centered

HTML Canvas : text doesn't appear at center of circle

I am trying to insert a text at the middle of a circle drawn with HTML Canvas, but its always appearing a little above the center. (I tried baseline, but it didn't work). I don't want to hard-coded the fillText co-ordinates.
var canvas = document.getElementById('completionStatus');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 200;
context.beginPath();
context.fillStyle = '#B8D9FE';
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fill();
context.strokeStyle = '#ffffff';
context.font = 'bold 130pt Calibri';
context.textAlign = 'center';
context.fillStyle = 'white';
context.fillText('70%', centerX, centerY);
context.stroke();
<canvas id="completionStatus" width="400" height="400"></canvas>
Here's a fiddle : http://jsfiddle.net/wku0j922/2/
Simply use the textBaseline property on the context. When both textBaseline is set to middle and textAlign is set to center you can place it exactly at the position of your circle center and it will be centered across the board.
var c1 = document.getElementById('c1');
var c2 = document.getElementById('c2');
var ct1 = c1.getContext('2d');
var ct2 = c2.getContext('2d');
c1.width = c2.width = 200;
c1.height = c2.height = 200;
ct1.font = ct2.font = '20px Helvetica';
ct1.textAlign = ct2.textAlign = 'center';
ct2.textBaseline = 'middle';
ct1.beginPath();
ct1.arc(100,100,99,0,Math.PI * 2);
ct1.stroke();
ct1.closePath();
ct2.beginPath();
ct2.arc(100,100,99,0,Math.PI * 2);
ct2.stroke();
ct2.closePath();
ct1.fillText('textBaseline not set', 100, 100);
ct2.fillText('textBaseline middle', 100, 100);
<canvas id="c1"></canvas>
<canvas id="c2"></canvas>
Here is it implemented in your snippet:
var canvas = document.getElementById('completionStatus');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 200;
context.beginPath();
context.fillStyle = '#B8D9FE';
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fill();
context.strokeStyle = '#ffffff';
context.font = 'bold 130pt Calibri';
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillStyle = 'white';
context.fillText('70%', centerX, centerY);
context.stroke();
<canvas id="completionStatus" width="400" height="400"></canvas>
Docs: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textBaseline
Declaring the textBaseline prior to defining the fillText seems to work.
var canvas = document.getElementById('completionStatus');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 200;
context.beginPath();
context.fillStyle = '#B8D9FE';
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fill();
context.strokeStyle = '#ffffff';
context.font = 'bold 130pt Calibri';
context.textAlign = 'center';
context.fillStyle = 'white';
// Defining the `textBaseline`…
context.textBaseline = "middle";
context.fillText('70%', centerX, centerY);
context.stroke();
#completionStatus {
border: 1px solid #000;
}
<canvas id="completionStatus" width="500" height="500"></canvas>
Canvas puts the text baseline in vertical centrum.
To truly center the text, you need to compensate for the font size:
context.font = 'bold ' + radius + 'px Calibri';
context.fillText('70%', centerX, centerY + Math.floor(radius/4));
I changed the centerY property to 300 and it seemed to have worked.
context.fillText('70%', centerX, 300);

How to add rectangle/arrow to my canvas line?

I have this code to show wind direction on html canvas:
var x, y, r, ctx, radians;
ctx = window.compass.getContext("2d");
radians = 0.0174533 * (10 - 90);
x = ctx.canvas.width / 2;
y = ctx.canvas.height / 2;
r = x * 0.8;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height );
ctx.beginPath();
ctx.strokeStyle = "red"
ctx.fillStyle = "rgba(255,0,0,0.5)";
ctx.lineCap = 'square';
ctx.shadowOffsetX = 4;
ctx.shadowOffsetY = 4;
ctx.shadowBlur = 2;
ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
ctx.lineWidth = 10;
ctx.moveTo(x, y);
ctx.lineTo(x + r * Math.cos(radians), y + r * Math.sin(radians));
ctx.stroke();
I want to add arrowhead to the start point of the line, i.e
x = ctx.canvas.width / 2;
y = ctx.canvas.height / 2;
how can I do this?
Creating a reusable wind-arrow is fairly straightforward:
Create your shadowed arrow on an in-memory canvas:
var memCanvas=document.createElement('canvas')
Draw the in-memory canvas onto the visible canvas:
ctx.drawImage(memCanvas,x,y);
Here's example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var cx=150;
var cy=150;
var angle=0;
var arrow=makeArrow(100,10,20,20,'red',4);
requestAnimationFrame(animate);
function animate(time){
ctx.clearRect(0,0,cw,ch);
drawArrow(cx,cy,angle);
angle+=Math.PI/180;
requestAnimationFrame(animate);
}
function drawArrow(cx,cy,radianAngle){
ctx.translate(cx,cy);
ctx.rotate(radianAngle);
ctx.drawImage(arrow,-arrow.width/2,-arrow.height/2);
ctx.rotate(-radianAngle);
ctx.translate(-cx,-cy);
}
function makeArrow(length,lineHeight,arrowLength,arrowHeight,fillcolor,shadowoffset){
var lineTop=(arrowHeight-lineHeight)/2;
var arrowLeft=length-arrowLength;
var c=document.createElement('canvas');
var ctx=c.getContext('2d');
c.width=length+shadowoffset;
c.height=arrowHeight+shadowoffset;
ctx.shadowOffsetX = shadowoffset;
ctx.shadowOffsetY = shadowoffset;
ctx.shadowBlur = 2;
ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
ctx.beginPath();
ctx.moveTo(0,lineTop);
ctx.lineTo(arrowLeft,lineTop);
ctx.lineTo(arrowLeft,0);
ctx.lineTo(length,arrowHeight/2);
ctx.lineTo(arrowLeft,arrowHeight);
ctx.lineTo(arrowLeft,lineTop+lineHeight);
ctx.lineTo(0,lineTop+lineHeight);
ctx.closePath();
ctx.fillStyle=fillcolor;
ctx.fill();
return(c);
}
body{ background-color:white; padding:10px; }
canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

Drawing Shadow of an object in Canvas

I want to draw one circle and a character with shadow on a canvas in a HTML page while loading the page and recreate the image on a button click. I am using this code:
window.onload = function() {
draw();
};
function draw(){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
var width = c.width;
var height = c.height;
//DRAW A CIRCLE
var centerX = Math.floor((Math.random() * width));
var centerY = Math.floor((Math.random() * height));
var radius = Math.floor(Math.random() * 50);
var color = '#f11';
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
//DRAW A CHARACTER WITH SHADOW
var c = "S";
ctx.font = "300% Verdana";
ctx.shadowBlur = 20;
ctx.shadowColor = "black";
ctx.shadowOffsetX = 20;
ctx.shadowOffsetY = 20;
ctx.fillStyle = "#111";
ctx.fillText(c, 10, 90);
}
In HTML I am calling draw function onclick() event of a button named Refresh.
For the first time it is giving desired output by drawing one circle and a character with shadow. As I click on the Refresh button it is drawing both the objects with shadow. I dont want to draw shadow of the circle. Can anyone please tell me the mistake I'm doing here.
You may want to use the CanvasRenderingContext2D.save() method :
window.onload = function() {
draw();
};
document.getElementById("canvas").addEventListener('click', draw);
function draw(){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
var width = c.width;
var height = c.height;
//DRAW A CIRCLE
var centerX = Math.floor((Math.random() * width));
var centerY = Math.floor((Math.random() * height));
var radius = Math.floor(Math.random() * 50);
var color = '#f11';
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
//DRAW A CHARACTER WITH SHADOW
//save the actual context
ctx.save();
var c = "S";
ctx.font = "300% Verdana";
ctx.shadowBlur = 20;
ctx.shadowColor = "black";
ctx.shadowOffsetX = 20;
ctx.shadowOffsetY = 20;
ctx.fillStyle = "#111";
ctx.fillText(c, 10, 90);
//restore it
ctx.restore();
}
canvas{border:1px solid;}
<canvas id="canvas" width="400" height="200"></canvas>

How to draw circles in HTML5 canvas with text in them

Seemed simple enough to draw circles and text in an HTML5 canvas, but I get non-intuitive behavior. The circles get drawn nice and pretty, then the more circles I draw, the older circles become more and more octagonal shaped. Very strange to me... Also, the text disappears from the old circles and only appears on the last circle drawn. What's the proper way to do this with canvases?
$("#circles_container").on("click", "#circles_canvas", function(event) {
var canvas = document.getElementById('circles_canvas');
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
var w = 16;
var x = event.pageX;
var y = Math.floor(event.pageY-$(this).offset().top);
ctx.fillStyle = "rgb(200,0,0)";
ctx.arc(x, y, w/2, 0, 2 * Math.PI, false);
ctx.fill();
ctx = canvas.getContext("2d");
ctx.font = '8pt Calibri';
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.fillText('0', x, y+3);
}
});
Just add this near the start of your function :
ctx.beginPath();
You were drawing a path always longer.
Demo in Stack Snippets & JS Fiddle (click on the canvas)
var canvas = document.getElementById('circles_canvas');
canvas.addEventListener("click", function(event) {
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
var w = 16;
var x = Math.floor(event.pageX-this.offsetLeft);
var y = Math.floor(event.pageY-this.offsetTop);
ctx.beginPath();
ctx.fillStyle = "rgb(200,0,0)";
ctx.arc(x, y, w/2, 0, 2 * Math.PI, false);
ctx.fill();
ctx.font = '8pt Calibri';
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.fillText('0', x, y+3);
}
})
canvas {
border: 1px solid black;
}
<h1>Click Canvas Below</h1>
<canvas id="circles_canvas"></canvas>

Categories