How rotate each figure by 90 degrees? - javascript

I'm trying to draw a coordinate system. I have a problem with the horizontal axis. I need to turn every number by 90 degrees.
my attempt:
var canvasGraphElem = document.getElementById("canvasGraph");
canvasGraphElem.width = 300;
canvasGraphElem.height = 200;
var ctx = canvasGraphElem.getContext('2d');
for(var i = 0; i <= 300; i = i + 30) {
ctx.save();
ctx.font = "10px Arial";
ctx.textAlign = "right";
ctx.translate(140, 140);
ctx.rotate(-Math.PI/2);
ctx.fillText(i, 0 + i, 0 - 25);
ctx.restore();
};
jsfiddle
The result should look like this:
Image is teal with numbers

You can approach this two ways:
Rotating text using local transformation. This allows you to rotate the text independently an at any angle and it's easier to place text and "logic" locations, but it requires a few more steps.
Rotate the whole context at once. This require you to "switch" axis as x axis is now y, and vica verse. It also limit the rotation to 90° and you have to think in terms of switched axis.
Method 1
var ctx = document.querySelector("canvas").getContext("2d");
ctx.font = "10px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
for(var i = 0; i <= 300; i += 30) {
ctx.setTransform(1, 0, 0, 1, 10 + i, 30); // absolute transform
ctx.rotate(-Math.PI*0.25); // any angle (demo 45°)
ctx.fillText(i, 0, 0);
};
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transforms
<canvas></canvas>
Method 2
var ctx = document.querySelector("canvas").getContext("2d");
ctx.font = "10px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.translate(20, 30); // set pivot
ctx.rotate(-Math.PI*0.5); // rotate canvas -90° around pivot
for(var i = 0; i <= 300; i += 30) {
ctx.fillText(i, 10, i); // increase y, since now "y=x"
};
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transforms
<canvas></canvas>

Related

Why do we have to rotate main canvas when trying rotate sprite image?

In every tutorial that I could find for how to rotate a sprite image on a canvas the canvas itself is rotated before applying sprite to it:
function drawSprite(sprite, x, y, deg)
{
const width = sprite.width / 2,
height = sprite.height / 2;
x = x + width;
y = y + height;
//clear main canvas
mainCtx.fillRect(0, 0, mainCanvas.width, mainCanvas.height);
// move origin to the coordinates of the center where sprite will be drawn
mainCtx.translate(x, y);
// rotate canvas
mainCtx.rotate(deg);
// draw sprite
mainCtx.drawImage(sprite, -width, -height);
// restore previous rotation and origin
mainCtx.rotate(-deg);
mainCtx.translate(-x, -y);
}
//never mind the rest
const mainCtx = mainCanvas.getContext("2d"),
sprite = (() =>
{
const canvas = document.createElement("canvas"),
ctx = canvas.getContext("2d"),
width = canvas.width = ctx.width = 100,
height = canvas.height = ctx.height = 50;
ctx.font = '20px arial';
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "lightgreen";
ctx.fillRect(0, 0, width, height);
ctx.strokeRect(0, 0, width, height);
ctx.strokeText("my sprite", width/2, height/2);
return canvas;
})();
let r = 0;
const d = Math.sqrt(sprite.width *sprite.width + sprite.height*sprite.height),
w = mainCanvas.width = mainCtx.width = 400,
h = mainCanvas.height = mainCtx.height = 200;
mainCtx.fillStyle = "pink";
setInterval(() =>
{
const deg = r++*Math.PI/180;
let x = ((w-d)/2) + (Math.sin(deg)*((w-d)/2)),
y = ((h-d)/1.2) + (Math.cos(deg)*((h-d)/2));
drawSprite(sprite, x, y, deg);
}, 10);
<canvas id="mainCanvas"></canvas>
To me this is counterintuitive, why can't we rotate sprite itself before drawing it on main canvas? Why doesn't this work?
function drawSprite(sprite, x, y, deg)
{
const spriteCtx = sprite.getContext("2d");
//clear main canvas
mainCtx.fillRect(0, 0, mainCanvas.width, mainCanvas.height);
// rotate sprite
spriteCtx.rotate(deg);
// draw sprite
mainCtx.drawImage(sprite, x, y);
}
//never mind the rest
const mainCtx = mainCanvas.getContext("2d"),
sprite = (() =>
{
const canvas = document.createElement("canvas"),
ctx = canvas.getContext("2d"),
width = canvas.width = ctx.width = 100,
height = canvas.height = ctx.height = 50;
ctx.font = '20px arial';
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "lightgreen";
ctx.fillRect(0, 0, width, height);
ctx.strokeRect(0, 0, width, height);
ctx.strokeText("my sprite", width/2, height/2);
return canvas;
})();
let r = 0;
const d = Math.sqrt(sprite.width *sprite.width + sprite.height*sprite.height),
w = mainCanvas.width = mainCtx.width = 400,
h = mainCanvas.height = mainCtx.height = 200;
mainCtx.fillStyle = "pink";
setInterval(() =>
{
const deg = r++*Math.PI/180;
let x = ((w-d)/2) + (Math.sin(deg)*((w-d)/2)),
y = ((h-d)/1.2) + (Math.cos(deg)*((h-d)/2));
drawSprite(sprite, x, y, deg);
}, 10);
<canvas id="mainCanvas"></canvas>
Wouldn't it be faster rotate a 100x100 sprite vs 10000x10000 main canvas?
Because the drawImage function takes only x(s),y(s) coordinate and width(s),/height(s).
I.e it only ever draws a straight rectangle, there is no way to make it draw anything skewed.
So you have to rotate the context's Current Transformation Matrix (CTM), which is not the canvas, so that the drawing is transformed.
Note that drawing a bitmap as a rectangle is a very basic model for drawing APIs.
As for the speed, once again you don't rotate the canvas, only the CTM and this only affects the future drawings and costs almost nothing anyway.
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.font = "30px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.translate(150, 75);
const txtArr = [ "first", "second", "third", "fourth" ];
const colors = [ "red", "blue", "green", "orange" ];
for (let i = 0; i < txtArr.length; i++) {
ctx.fillStyle = colors[i];
ctx.fillText(txtArr[i], 0, 0);
// This doesn't rotate the previous drawings
ctx.rotate(Math.PI / txtArr.length);
}
<canvas></canvas>
So, yes, you could have your own drawImage(source, matrix) which would be something like
this.save();
this.setTransform(matrix);
this.drawImage(source, 0, 0);
this.restore();
But as you can see this means actually more operations per draw call, and thus performing two drawings on the same CTM would actually cost more than setting the CTM only once.

How do I change the ctx.fillStyle when the url changes?

so I am experimenting with 2d drawings in Javascript and what I am trying to do is change the ctx.fillStyle (which is the drawing colour) and change it to another colour when the URL changes.
Any help would be greatly appreciated. Here is a part of my code:
The codepen link for the animation: https://codepen.io/LudovicTomlo/pen/PEWEwJ
window.draw = setInterval(function() {
ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = "#00ff00";
ctx.font = font_size + "px Sawarabi Gothic";
if(location.pathname.endsWith("/401?e=1")) {
ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = "#ff0000";
ctx.font = font_size + "px Sawarabi Gothic";
}
for(var i = 0; i < rain.length; i++) {
// random character from the set
var text = chars[Math.floor(Math.random()*chars.length)];
ctx.fillText(text, i*font_size, rain[i]*font_size);
if(rain[i]*font_size > c.height && Math.random() > 0.975) {
rain[i] = 0;
}
//incrementing Y coordinate
rain[i]++;
}
}, speed);
}

HTML Canvas remove letter spacing on the beginning of a word

I have a canvas and I want to print words on it in horizontal and vertical orientation. The printing itself works fine but I have a somewhat annoying spacing at the beginning of the words, which becomes extremely visible on the vertical text like the EX on the example image.
I just created a little example which shows what I mean
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create a red line in position 150
ctx.strokeStyle = "red";
ctx.moveTo(150, 20);
ctx.lineTo(150, 170);
ctx.stroke();
ctx.font = "50px Arial";
// Show the different textAlign values
ctx.textAlign = "start";
ctx.fillText("EX", 150, 50);
ctx.textAlign = "end";
ctx.fillText("EX", 150, 100);
ctx.textAlign = "center";
ctx.fillText("EX", 150, 150);
<canvas id="myCanvas" width="300" height="200" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
Is there a way to place the beginning of the word at the point I am drawing to or is there a way to calculate the spacing at the beginning and then just subtract it from the starting point of the text?
The TextMetrics interface has actualBoundingBox[...] information that you can use to know by how much the actual bounding box is offset relatively to the textAlign and textBaseline lines.
So adding the measured actualBoundingBoxLeft to your horizontal position when writing LTR text with the "start" text-align will remove this gap.
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
const input = document.querySelector("input");
input.oninput = draw;
draw();
function draw() {
const txt = input.value;
ctx.clearRect(0, 0, c.width, c.height);
ctx.fillStyle = "black";
// Create a red line in position 150
ctx.strokeStyle = "red";
ctx.moveTo(150, 20);
ctx.lineTo(150, 180);
ctx.stroke();
ctx.font = "50px Arial";
ctx.textBaseline = "top"; // needed for the ascent and decsent measurements
// Show the original textAlign
ctx.textAlign = "start";
ctx.fillText(txt, 150, 30);
// fixed
ctx.fillStyle = "green";
const metrics = ctx.measureText(txt);
ctx.fillText(txt, 150 + metrics.actualBoundingBoxLeft, 110);
// Draw the box around our text
ctx.translate( 150, 110 );
const x = 0; // we already did offset by actualBoundingBoxLeft
const y = metrics.actualBoundingBoxAscent * -1;
const width = metrics.actualBoundingBoxRight + metrics.actualBoundingBoxLeft;
const height = metrics.actualBoundingBoxDescent + metrics.actualBoundingBoxAscent;
ctx.strokeRect(x, y, width, height);
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
<input value="Éxy"><br>
<canvas id="myCanvas" width="300" height="200" style="border:1px solid #d3d3d3;"></canvas>

how to make an object turn around a point in html5 canvas

The problem is demonstrated in the image below
In other words, how to exactly compute the x and y coordinates for every frame?
ctx.arc(x,y,radius,0,pi*2,false)
because after incrementing one coordinate, I have a problem how to compute the other
I tried this but doesn't work
var step=2,x=100,y=100,r=50,coordinates=[[x,y-r]];
for(var i=1;i <r;i+=step){
bx=x;
x+=step;
y=y-Math.sqrt(Math.pow(r,2)-Math.pow(bx-x,2))
coordinates[i]=[x,y];
}
a jsfiddle will be appreciated.
var canvas = document.querySelector("#c");
var ctx = canvas.getContext("2d");
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var speed = 10; // Lower is faster
function animate(t){
ctx.save();
ctx.clearRect (0 , 0 ,canvas.width ,canvas.height );
ctx.translate(canvas.width/2, canvas.height/2);
// First circle
ctx.beginPath();
ctx.arc(0, 0, 5, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
// rotate + move along
ctx.rotate((t/speed)/100);
ctx.translate(100,0);
// Orbiting cirle
ctx.beginPath();
ctx.arc(0, 0, 10, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
ctx.restore();
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
canvas {
border: 1px solid black;
}
<canvas id="c" width="512" height="512"></canvas>

Drawing text with an outer stroke with HTML5's 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();

Categories