How to remove straight lines from multiple rotated arc on canvas? - javascript

I want to create Star Trail on canvas.
The idea to create it, i have to draw multiple images that increment size, and some calculation for the next image position. Store multiple image in array. Choose the image randomly each draw and draw it with different angle each image.
I made it.
var canvas=document.getElementById('canvas'),ctx=canvas.getContext('2d');
var starsimage=['https://1.bp.blogspot.com/-prwJzDDwQRU/XTjNfQhQnDI/AAAAAAAACBo/wpbhqkfc-9wQQeg95O6poFbFyu77q4vdACLcBGAs/s1600/CircleWhite100.png','https://1.bp.blogspot.com/-lm4F2UOMCdE/XTjNghXjrOI/AAAAAAAACB0/L6pya6HQk0cU5R5RP9Wo_-Bm_UhO_qCawCLcBGAs/s1600/CircleWhite75.png','https://1.bp.blogspot.com/-7ennrlohEo0/XTjNfoji8KI/AAAAAAAACBw/G0SQhFEZ0IMMf2z3g_Mvbon97BMktSw-QCLcBGAs/s1600/CircleWhite50.png','https://1.bp.blogspot.com/-I7aeA-F4OWY/XTjNfiO-rxI/AAAAAAAACBs/lKYC-SmaWSQWc0PoPVdgCHeyDUPdoJd7gCLcBGAs/s1600/CircleWhite25.png','https://1.bp.blogspot.com/-V2Ak6YU2XNA/XTjNh7iIwZI/AAAAAAAACCA/tNo5Ho6iC4gndoftPJfSCInGqgyfcd6nQCLcBGAs/s1600/TrailBlue100.png','https://1.bp.blogspot.com/-ylpi3AZvces/XTjNi7uy1kI/AAAAAAAACCM/uWZ7_zYRXXQN4q3QRSngCFeT5RoEeG4xgCLcBGAs/s1600/TrailBlue75.png','https://1.bp.blogspot.com/-NoPiS9k0o0U/XTjNivmKVjI/AAAAAAAACCI/gZzDMn9zomMWrQc2hhKfNB9JK0ruh2wyQCLcBGAs/s1600/TrailBlue50.png','https://1.bp.blogspot.com/-KYkWDwtmS7A/XTjNiSE8Y_I/AAAAAAAACCE/jDyTIbJqBBs3FP1tyGFICjShyx_GCCy0gCLcBGAs/s1600/TrailBlue25.png'];
var stars=new Array();var starsloaded=0;
var xpos=0,ypos=0,w=25,h=25,ix=0,xa=25,ya=25,rot=0,ang=0;
for(var i=0;i<starsimage.length;i++){//load images
stars[i]=new Image();stars[i].src=starsimage[i];
stars[i].onload=function(){starsloaded++;if(starsloaded==starsimage.length){
draw();
}}
}
function minmaxdraw(min,max){return Math.floor(Math.random() * (max - min + 1)) + min}
function randomindeximage(l){return Math.floor(Math.random()*l)}
function draw(){
xpos=canvas.width/2;ypos=canvas.height/2;
for(var i=0;i<500;i++){//500 images
xy=minmaxdraw(2,4);//gap randomly
ix=randomindeximage(starsimage.length);
w+=xy;h+=xy;ang=minmaxdraw(0,359);
if(i>0){xa=w-xa;ya=h-ya;xpos=xpos-xa/2;ypos=ypos-ya/2;
ctx.save();
ctx.translate(xpos+w/2,ypos+h/2);
rot=ang*Math.PI/180;ctx.rotate(rot);
ctx.drawImage(stars[ix],-w/2,-h/2,w,h);
ctx.restore();
xa=w;ya=h;
}
else{ctx.drawImage(stars[ix],xpos,ypos,w,h)}
}
}
body{margin:0;padding:0;position:relative;background:#101010;height:580px;width:100%}
#canvas{z-index:2;background-color:transparent;position:absolute;width:100vw;left:50%;top:50%;transform:translate(-50%,-50%)}
body:before{content:'';z-index:1;position:absolute;width:100%;height:100%;left:0;top:0;background:linear-gradient(15deg, #1458ac, #000);}
<canvas id="canvas" width="640" height="580"></canvas>
But. the quality is bad. Because the image size is static, blurry if the increment width is larger than actually image size, and the small stars is barely visible
I think, it's better to create it with multiple arc.
The idea is same, i have to draw multiple arc. But, i'm dummy, i made with two canvas, different angle each canvas. (It's actually same with my work before, but at the time, i use 1 image that have cutted circle). Because if i made it only on one canvas, the straight line appears. So, i draw multiple arc in each canvas. It works, and no straight line appears. (It's still basic arc)
var canvas1=document.getElementById('canvas1'),ctx=canvas1.getContext('2d'),canvas2=document.getElementById('canvas2'),ctx2=canvas2.getContext('2d');var xy=0;var angle=new Array();
function minmaxdraw(min,max){return Math.floor(Math.random() * (max - min + 1)) + min}
function randomindeximage(l){return Math.floor(Math.random()*l)}
function draw1(){
var xpos=canvas1.width/2;var ypos=canvas1.height/2;var r=15,ang=0;
ctx.beginPath();
for(var i=0;i<55;i++){
r+=minmaxdraw(4,9);
ctx.moveTo(xpos + r, ypos);
ctx.arc(xpos, ypos, r, 0, 1.5*Math.PI,true);
}ctx.stroke();
}
function draw2(){
var xpos=canvas2.width/2;var ypos=canvas2.height/2;var r=15;
ctx2.beginPath();
for(var t=0;t<55;t++){
r+=minmaxdraw(4,9);
ctx2.moveTo(xpos, ypos + r);
ctx2.arc(xpos, ypos, r, Math.PI / 2, Math.PI);
}ctx2.stroke();
}
draw1();draw2();
body{margin:0;padding:0;position:relative;height:480px;width:100%}
.canvas{background-color:transparent;position:absolute;width:100vw;left:50%;top:50%;margin:-50% 0 0 -50%}
<canvas id='canvas1' class='canvas' width='640' height='480'></canvas>
<canvas id='canvas2' class='canvas' width='640' height='480'></canvas>
It's not rotated yet.
So, if i want make circle trail, i have to rotate each arc randomly like i did before with image, but the problem is here. The straight lines come wickedly.
var canvas1=document.getElementById('canvas1'),ctx=canvas1.getContext('2d'),canvas2=document.getElementById('canvas2'),ctx2=canvas2.getContext('2d');var xy=0;var angle=new Array();
function minmaxdraw(min,max){return Math.floor(Math.random() * (max - min + 1)) + min}
function randomindeximage(l){return Math.floor(Math.random()*l)}
function draw1(){
var xpos=canvas1.width/2;var ypos=canvas1.height/2;
var r=15,ang=0,dx=0,dy=0;
ctx.beginPath();
for(var i=0;i<55;i++){//200 images
ang=minmaxdraw(0,359);
dx=minmaxdraw(0,canvas1.width),dy=minmaxdraw(0,canvas1.height);
r+=minmaxdraw(3,7);
ang=Math.atan2(dx-xpos,dy-ypos);angle[i]=ang;
ctx.moveTo(xpos, ypos);
ctx.arc(xpos, ypos, r, ang + 0 * Math.PI, ang + Math.PI * 1.5,true);
}ctx.stroke();
}
function draw2(){
var xpos=canvas2.width/2;var ypos=canvas2.height/2;var r=15;
ctx2.beginPath();
for(var t=0;t<55;t++){
r+=minmaxdraw(3,7);
ctx2.moveTo(xpos, ypos + r);
ctx2.arc(xpos, ypos, r, angle[t] + Math.PI / 2, angle[t] + Math.PI);
}ctx2.stroke();
}
draw1();draw2();
body{margin:0;padding:0;position:relative;height:480px;width:100%}
.canvas{background-color:transparent;position:absolute;width:100vw;left:50%;top:50%;margin:-50% 0 0 -50%}
<canvas id='canvas1' class='canvas' width='640' height='480'></canvas>
<canvas id='canvas2' class='canvas' width='640' height='480'></canvas>
Is there any solution to remove that straight lines?

Not sure why you have the calls to moveTo and maybe I just didn't understand the question but I just moved beginPath and stroke inside the loops.
var canvas1 = document.getElementById('canvas1'),
ctx = canvas1.getContext('2d'),
canvas2 = document.getElementById('canvas2'),
ctx2 = canvas2.getContext('2d');
var xy = 0;
var angle = new Array();
function minmaxdraw(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
function randomindeximage(l) {
return Math.floor(Math.random() * l)
}
function draw1() {
var xpos = canvas1.width / 2;
var ypos = canvas1.height / 2;
var r = 15,
ang = 0,
dx = 0,
dy = 0;
for (var i = 0; i < 55; i++) { //200 images
ang = minmaxdraw(0, 359);
dx = minmaxdraw(0, canvas1.width), dy = minmaxdraw(0, canvas1.height);
r += minmaxdraw(3, 7);
ang = Math.atan2(dx - xpos, dy - ypos);
angle[i] = ang;
ctx.beginPath();
ctx.arc(xpos, ypos, r, ang + 0 * Math.PI, ang + Math.PI * 1.5, true);
ctx.stroke();
}
}
function draw2() {
var xpos = canvas2.width / 2;
var ypos = canvas2.height / 2;
var r = 15;
for (var t = 0; t < 55; t++) {
r += minmaxdraw(3, 7);
ctx2.beginPath();
ctx2.arc(xpos, ypos, r, angle[t] + Math.PI / 2, angle[t] + Math.PI);
ctx2.stroke();
}
}
draw1();
draw2();
body {
margin: 0;
padding: 0;
position: relative;
height: 550px;
width: 100%
}
.canvas {
background-color: transparent;
position: absolute;
width: 100vw;
left: 50%;
top: 50%;
margin: -50% 0 0 -50%
}
<canvas id='canvas1' class='canvas' width='640' height='480'></canvas>
<canvas id='canvas2' class='canvas' width='640' height='480'></canvas>
Also I don't understand why you have 2 canvases. It works fine with just one
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
var xy = 0;
var angle = new Array();
function minmaxdraw(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
function randomindeximage(l) {
return Math.floor(Math.random() * l)
}
function draw1() {
var xpos = canvas.width / 2;
var ypos = canvas.height / 2;
var r = 15,
ang = 0,
dx = 0,
dy = 0;
for (var i = 0; i < 55; i++) { //200 images
ang = minmaxdraw(0, 359);
dx = minmaxdraw(0, canvas.width), dy = minmaxdraw(0, canvas.height);
r += minmaxdraw(3, 7);
ang = Math.atan2(dx - xpos, dy - ypos);
angle[i] = ang;
ctx.beginPath();
ctx.arc(xpos, ypos, r, ang + 0 * Math.PI, ang + Math.PI * 1.5, true);
ctx.stroke();
}
}
function draw2() {
var xpos = canvas.width / 2;
var ypos = canvas.height / 2;
var r = 15;
for (var t = 0; t < 55; t++) {
r += minmaxdraw(3, 7);
ctx.beginPath();
ctx.arc(xpos, ypos, r, angle[t] + Math.PI / 2, angle[t] + Math.PI);
ctx.stroke();
}
}
draw1();
draw2();
<canvas id='canvas' class='canvas' width='640' height='480'></canvas>
The reason you got lines before is all arc does is add points.
arc is effectively this
// pseudo code
function arc(x, y, radius, start, end) {
const numSegments = 100; // no idea what number real arc uses here
for (let i = 0; i < numSegments; ++i) {
const angle = start + (end - start) * i / numSegments;
ctx.lineTo(Math.cos(angle) * radius, Math.sin(angle) * radius);
}
}
As you can see the code above just adds the points around the arc. So if you do a
ctx.moveTo(x, y);
ctx.arc(x, y, ...);
you're adding a point in the center of the arc and then more points to the edge. That's why you're getting a line from the centers to the edge of each arc.
If you wanted to leave the code the same as you had it and just stroke all the arcs at once then you'd need to change the moveTo to move to the edge of the arc instead of the center.
ctx.moveTo(x + Math.cos(start) * radius, y + Math.sin(start) * radius);
ctx.arc(x, y, radius, start, ...);

Related

How to generate and animate a hexagonal sine wave in javascript after drawing a hexagon in HTML canvas?

After having tried sine and cosine wave animations, I am facing issues while animating a hexagonal wave with rotating radius. I am unable to get the diagonal wave lines to be straight in the wave. They come out slightly curled.
var hexStep = 0;
var hexID;
function drawAxes(context) {
var width = context.canvas.width;
var height = context.canvas.height;
context.beginPath();
context.strokeStyle = "rgb(128,128,128)";
context.lineWidth = 1;
// X-axis
context.moveTo(0, height / 2);
context.lineTo(width, height / 2);
// Sine Wave starting wall
context.moveTo(width / 4, 0);
context.lineTo(width / 4, height);
// Sine Wave Y-axis
context.moveTo((2.5 * width) / 4, 0);
context.lineTo((2.5 * width) / 4, height);
// Shape Y-axis
context.moveTo(width / 8, 0);
context.lineTo(width / 8, height);
context.stroke();
}
// Hexagon
function drawHexagon(context, x, y, r, side) {
var width = context.canvas.width;
var height = context.canvas.height;
var angle = (2 * Math.PI) / side;
context.beginPath();
context.strokeStyle = "midnightblue";
context.lineWidth = 2;
context.moveTo(x + r, y);
var hx = 0;
var hy = 0;
for (var i = 1; i <= side; i++) {
hx = x + r * Math.cos(angle * i);
hy = y + r * Math.sin(angle * i);
context.lineTo(hx, hy);
}
context.stroke();
}
function getHexagonalWave(context, x, y, r, side, step, freq) {
var width = context.canvas.width;
var height = context.canvas.height;
var angle = (2 * Math.PI) / side;
var inr = r * Math.sqrt(0.75);
context.beginPath();
context.strokeStyle = "midnightblue";
context.lineWidth = 2;
context.moveTo(x, y);
var sf = step / freq;
var hr = inr / Math.cos(((sf + angle / 2) % angle) - angle / 2);
var hx = x + hr * Math.sin(sf);
var hy = y - hr * Math.cos(sf);
context.lineTo(hx, hy);
var wx = width / 4;
context.moveTo(hx, hy);
context.lineTo(wx, hy);
context.moveTo(wx, hy);
var hvr = 0;
var wvx = 0;
var wvy = 0;
var id = 0;
for (var i = 0; i < width; i++) {
hvr = inr / Math.cos((((i + step) / freq + angle / 2) % angle) - angle / 2);
wvy = y - hvr * Math.cos((i + step) / freq);
wvx = wx + hvr * Math.sin((i + step) / freq);
context.lineTo(wx + i, wvy);
}
context.stroke();
}
function doGenerateHexagonalWave() {
var canvas = document.getElementById("canvas3");
var context = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var x = width / 8;
var y = height / 2;
var r = (1.5 * height) / 4;
var side = 6;
var freq = 60;
context.clearRect(0, 0, width, height); // Check
drawAxes(context);
drawHexagon(context, x, y, r, side);
getHexagonalWave(context, x, y, r, side, hexStep, freq);
hexStep++;
hexID = window.requestAnimationFrame(doGenerateHexagonalWave);
}
function doStopHexagonalWave() {
window.cancelAnimationFrame(hexID);
}
function doClearHexagonalWave() {
window.cancelAnimationFrame(hexID);
var canvas = document.getElementById("canvas3");
var context = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
context.clearRect(0, 0, width, height);
}
body {
background-color:darkgray;
margin-left: 10px;
}
h1 {
margin: 5px;
}
hr {
border: 1px solid;
}
canvas {
margin: 5px;
margin-bottom: -8px;
background-color:lightgrey;
/*
width: 500px;
height: 100px;
*/
}
p {
margin-left: 5px;
}
<h1>Hexagonal Wave</h1>
<hr>
<div>
</p>
<canvas id="canvas3" width="800" height="200">
</canvas>
<p>
<input type="button" value="Generate" onclick="doGenerateHexagonalWave()"/>
<input type="button" value="Stop" onclick="doStopHexagonalWave()" />
<input type="button" value="Clear" onclick="doClearHexagonalWave()" />
</p>
</div>
How do I get the angles to form straight edges between vertices in the wave by using the variable 'wvx' in the for loop ? Can't seem to figure it out!

How to transalate hexagon in canvas html using typescript

i drew a hexagon on canvas in html and i want to tranaslate the hexagon in canvas when i use a translate method it doesn't translate the hexagon but when i translate it does translate when i use the rectangle .
var canvas:HTMLCanvasElement = document.getElementById("myCanvas");
var context:CanvasRenderingContext2D = canvas.getContext("2d");
var x = 300;
var y = 100;
context.beginPath();
context.moveTo(x, y);
x = x + 120;
y = y + 100;
context.lineTo(x, y);
y = y + 120;
context.lineTo(x, y);
x = x - 125;
y = y + 100;
context.lineTo(x, y);
x = x - 125;
y = y - 100;
context.lineTo(x, y);
y = y - 120;
context.lineTo(x, y);
x = x + 130;
y = y - 100;
context.lineTo(x, y);
context.strokeStyle = "red";
context.lineWidth = 4;
context.fillStyle = "blue";
context.fill();
context.translate(400,400);
context.fillStyle = "blue";
context.fill();
context.save();
context.fillRect(10, 10, 100, 50);
context.translate(70, 70);
context.fillRect(10, 10, 100, 50);
Edit 1:
according to the #helder gave the answer I've made the changes but translate is not working
function hexagon(x:number, y:number, r:number, color:string) {
context.beginPath();
var angle = 0
for (var j = 0; j < 6; j++) {
var a = angle * Math.PI / 180
var xd = r * Math.sin(a)
var yd = r * Math.cos(a)
context.lineTo(x + xd, y + yd);
angle += 360 / 6
}
context.fillStyle = color;
context.fill();
context.translate(70,70);
context.fill();
}
hexagon(100, 100, 50, "red")
I would try to create a function that draws the hexagon that way you don't have to use translate.
See below
c = document.getElementById("canvas");
context = c.getContext("2d");
function hexagon(x, y, r, color) {
context.beginPath();
var angle = 0
for (var j = 0; j < 6; j++) {
var a = angle * Math.PI / 180
var xd = r * Math.sin(a)
var yd = r * Math.cos(a)
context.lineTo(x + xd, y + yd);
angle += 360 / 6
}
context.fillStyle = color;
context.fill();
}
hexagon(50, 50, 30, "red")
hexagon(40, 40, 10, "blue")
hexagon(60, 60, 10, "lime")
<canvas id=canvas >
Here is a break down of function hexagon(x, y, r, color)
it takes the center of the hexagon (x,y) a radius (r) and color
we loop over the six vertices and draw lines
the calculations are just a bit of trigonometry nothing fancy
With that we can draw hexagons at any location we want.
and that same function you can easily refactor to draw an octagon or other polygons.
Here is an animated version of those hexagons
c = document.getElementById("canvas");
context = c.getContext("2d");
delta = 0
function hexagon(x, y, r, color) {
context.beginPath();
var angle = 0
for (var j = 0; j < 6; j++) {
var a = angle * Math.PI / 180
var xd = r * Math.sin(a)
var yd = r * Math.cos(a)
context.lineTo(x + xd, y + yd);
angle += 360 / 6
}
context.fillStyle = color;
context.fill();
}
function draw() {
context.clearRect(0, 0, c.width, c.height)
var xd = 10 * Math.sin(delta)
var yd = 10 * Math.cos(delta)
hexagon(50 - xd, 50 - yd, 30, "red")
hexagon(40 + xd, 40 + yd, 10, "blue")
delta += 0.2
}
setInterval(draw, 100);
<canvas id=canvas>
As you can see there is no need to use translate

html canvas check that object is in angle

I have a circle, and a object.
I want to draw a circle segment with specified spread, and next check that the object is in defined angle, if it is, angle color will be red, otherwise green. But my code does not work in some cases...
in this case it work:
in this too:
but here it isn't:
I know that my angle detection code part is not perfect, but I have no idea what I can do.
This is my code:
html:
<html>
<head></head>
<body>
<canvas id="c" width="800" height="480" style="background-color: #DDD"></canvas>
<script src="script.js"></script>
</body>
</html>
js:
window.addEventListener('mousemove', updateMousePos, false);
var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
//mouse coordinates
var mx = 0, my = 0;
draw();
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height);
//object coordinates
var ox = 350, oy = 260;
context.beginPath();
context.arc(ox,oy,5,0,2*Math.PI);
context.fill();
//circle
var cx = 400, cy = 280;
var r = 100;
var segmentPoints = 20;
var circlePoints = 40;
var spread = Math.PI / 2;
var mouseAngle = Math.atan2(my - cy, mx - cx); //get angle between circle center and mouse position
context.beginPath();
context.strokeStyle = "blue";
context.moveTo(cx + r, cy);
for(var i=0; i<circlePoints; i++)
{
var a = 2 * Math.PI / (circlePoints - 1) * i;
var x = cx + Math.cos(a) * r;
var y = cy + Math.sin(a) * r;
context.lineTo(x, y);
}
context.lineTo(cx + r, cy);
context.stroke();
var objAngle = Math.atan2(oy - cy, ox - cx);
var lowerBorder = mouseAngle - spread / 2;
var biggerBorder = mouseAngle + spread / 2;
/////////////////////////////////////////////ANGLES DETECTION PART
if(objAngle >= lowerBorder && objAngle <= biggerBorder ||
objAngle <= biggerBorder && objAngle >= lowerBorder)
{
context.strokeStyle = "red";
}
else
context.strokeStyle = "green";
context.lineWidth = 3;
//angle center line
context.beginPath();
context.moveTo(cx, cy);
context.lineTo(cx + Math.cos(mouseAngle) * r * 2, cy + Math.sin(mouseAngle) * r * 2);
context.stroke();
//draw spread arc
context.beginPath();
context.moveTo(cx, cy);
for(var i=0; i<segmentPoints; i++)
{
var a = mouseAngle - spread / 2 + spread / (segmentPoints - 1) * i;
var x = cx + Math.cos(a) * r;
var y = cy + Math.sin(a) * r;
context.lineTo(x, y);
}
context.lineTo(cx, cy);
context.stroke();
//show degrees
context.font = "20px Arial";
context.fillText((lowerBorder * 180 / Math.PI).toFixed(2), Math.cos(lowerBorder) * r + cx, Math.sin(lowerBorder) * r + cy);
context.fillText((biggerBorder * 180 / Math.PI).toFixed(2), Math.cos(biggerBorder) * r + cx, Math.sin(biggerBorder) * r + cy);
context.fillText((mouseAngle * 180 / Math.PI).toFixed(2), Math.cos(mouseAngle) * r + cx, Math.sin(mouseAngle) * r + cy);
//update
setTimeout(function() { draw(); }, 10);
}
//getting mouse coordinates
function updateMousePos(evt)
{
var rect = document.getElementById("c").getBoundingClientRect();
mx = evt.clientX - rect.left;
my = evt.clientY - rect.top;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin: auto;
left: 0;
right: 0;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
// Rotation here is being measured in Radians
// Given two 2D vectors A & B, the angle between them can be drawn from this formula
// A dot B = length(a) * length(b) * cos(angle)
// if the vectors are normalized (the length is 1) the formula becomes
// A dot B = cos(angle)
// angle = acos(a.x * b.x + a.y * b.y)
// So here you are concerned with the direction of the two vectors
// One will be the vector facing outward from the middle of your arc segment
// The other will be a directional vector from the point you want to do collision with to the center
// of the circle
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var bounds = {top: 0.0, left: 0.0};
var circle = {
x: (canvasWidth * 0.5)|0,
y: (canvasHeight * 0.5)|0,
radius: 50.0,
rotation: 0.0, // In Radians
arcSize: 1.0
};
var point = {
x: 0.0,
y: 0.0
};
window.onmousemove = function(e) {
point.x = e.clientX - bounds.left;
point.y = e.clientY - bounds.top;
}
// runs after the page has loaded
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
bounds = canvas.getBoundingClientRect();
ctx = canvas.getContext("2d");
loop();
}
function loop() {
// Update Circle Rotation
circle.rotation = circle.rotation + 0.025;
if (circle.rotation > 2*Math.PI) {
circle.rotation = 0.0;
}
// Vector A (Point Pos -> Circle Pos)
var aX = circle.x - point.x;
var aY = circle.y - point.y;
var aLength = Math.sqrt(aX * aX + aY * aY);
// Vector B (The direction the middle of the arc is facing away from the circle)
var bX = Math.sin(circle.rotation);
var bY =-Math.cos(circle.rotation); // -1 is facing upward, not +1
var bLength = 1.0;
// Normalize vector A
aX = aX / aLength;
aY = aY / aLength;
// Are we inside the arc segment?
var isInsideRadius = aLength < circle.radius;
var isInsideAngle = Math.abs(Math.acos(aX * bX + aY * bY)) < circle.arcSize * 0.5;
var isInsideArc = isInsideRadius && isInsideAngle;
// Clear the screen
ctx.fillStyle = "gray";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
// Draw the arc
ctx.strokeStyle = isInsideArc ? "green" : "black";
ctx.beginPath();
ctx.moveTo(circle.x,circle.y);
ctx.arc(
circle.x,
circle.y,
circle.radius,
circle.rotation - circle.arcSize * 0.5 + Math.PI * 0.5,
circle.rotation + circle.arcSize * 0.5 + Math.PI * 0.5,
false
);
ctx.lineTo(circle.x,circle.y);
ctx.stroke();
// Draw the point
ctx.strokeStyle = "black";
ctx.fillStyle = "darkred";
ctx.beginPath();
ctx.arc(
point.x,
point.y,
5.0,
0.0,
2*Math.PI,
false
);
ctx.fill();
ctx.stroke();
// This is better to use then setTimeout()
// It automatically syncs the loop to 60 fps for you
requestAnimationFrame(loop);
}
</script>
</body>
</html>

Simple shape transformation star -> circle canvas

I was just wondering if it is possible to transform between two shapes using just canvas.
ie: star to a cirle.
this is what I have so far:
var canvas,
ctx,
length = 15;
canvas = document.getElementById("star");
ctx = canvas.getContext("2d");
ctx.translate(30, 30);
ctx.rotate((Math.PI * 1 / 10));
for (var i = 5; i--;) {
ctx.lineTo(0, length);
ctx.translate(0, length);
ctx.rotate((Math.PI * 2 / 10));
ctx.lineTo(0, -length);
ctx.translate(0, -length);
ctx.rotate(-(Math.PI * 6 / 10));
}
ctx.lineTo(0, length);
ctx.closePath();
ctx.fill();
Here is a basic transition in pure canvas. Using arcs instead of lines is left as an exercise for the reader ;)
http://jsfiddle.net/pD9CM/
var canvas,
ctx,
length = 15;
canvas = document.getElementById("star");
ctx = canvas.getContext("2d");
var max = 50;
var inset = 0;
var direction = +1;
function draw() {
ctx.clearRect(0, 0, 300, 300);
ctx.beginPath();
var i = 11
while (i--) {
var angle = (i/10) * Math.PI * 2;
var distance = (i % 2 === 0) ? (max - inset) : max;
var pt = point(angle, distance);
if (i === 0) ctx.moveTo(pt.x + 150, pt.y + 150);
else ctx.lineTo(pt.x + 150, pt.y + 150);
}
ctx.fill();
if (inset < 0 || inset > 30) direction = -direction;
inset += direction;
}
function point(angle, distance) {
return {
x: Math.cos(angle) * distance,
y: Math.sin(angle) * distance
};
}
setInterval(draw, 20);

How Can I draw a Text Along arc path with HTML 5 Canvas?

I want to draw a canvas graphic like this flash animation:
http://www.cci.com.tr/tr/bizi-taniyin/tarihcemiz/
I drew six arcs and I want to write six words in these arcs. Any ideas?
I have a jsFiddle to apply text to any arbitrary Bezier curve definition. Enjoy http://jsfiddle.net/Makallus/hyyvpp8g/
var first = true;
startIt();
function startIt() {
canvasDiv = document.getElementById('canvasDiv');
canvasDiv.innerHTML = '<canvas id="layer0" width="300" height="300"></canvas>'; //for IE
canvas = document.getElementById('layer0');
ctx = canvas.getContext('2d');
ctx.fillStyle = "black";
ctx.font = "18px arial black";
curve = document.getElementById('curve');
curveText = document.getElementById('text');
$(curve).keyup(function(e) {
changeCurve();
});
$(curveText).keyup(function(e) {
changeCurve();
});
if (first) {
changeCurve();
first = false;
}
}
function changeCurve() {
points = curve.value.split(',');
if (points.length == 8) drawStack();
}
function drawStack() {
Ribbon = {
maxChar: 50,
startX: points[0],
startY: points[1],
control1X: points[2],
control1Y: points[3],
control2X: points[4],
control2Y: points[5],
endX: points[6],
endY: points[7]
};
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.beginPath();
ctx.moveTo(Ribbon.startX, Ribbon.startY);
ctx.bezierCurveTo(Ribbon.control1X, Ribbon.control1Y,
Ribbon.control2X, Ribbon.control2Y,
Ribbon.endX, Ribbon.endY);
ctx.stroke();
ctx.restore();
FillRibbon(curveText.value, Ribbon);
}
function FillRibbon(text, Ribbon) {
var textCurve = [];
var ribbon = text.substring(0, Ribbon.maxChar);
var curveSample = 1000;
xDist = 0;
var i = 0;
for (i = 0; i < curveSample; i++) {
a = new bezier2(i / curveSample, Ribbon.startX, Ribbon.startY, Ribbon.control1X, Ribbon.control1Y, Ribbon.control2X, Ribbon.control2Y, Ribbon.endX, Ribbon.endY);
b = new bezier2((i + 1) / curveSample, Ribbon.startX, Ribbon.startY, Ribbon.control1X, Ribbon.control1Y, Ribbon.control2X, Ribbon.control2Y, Ribbon.endX, Ribbon.endY);
c = new bezier(a, b);
textCurve.push({
bezier: a,
curve: c.curve
});
}
letterPadding = ctx.measureText(" ").width / 4;
w = ribbon.length;
ww = Math.round(ctx.measureText(ribbon).width);
totalPadding = (w - 1) * letterPadding;
totalLength = ww + totalPadding;
p = 0;
cDist = textCurve[curveSample - 1].curve.cDist;
z = (cDist / 2) - (totalLength / 2);
for (i = 0; i < curveSample; i++) {
if (textCurve[i].curve.cDist >= z) {
p = i;
break;
}
}
for (i = 0; i < w; i++) {
ctx.save();
ctx.translate(textCurve[p].bezier.point.x, textCurve[p].bezier.point.y);
ctx.rotate(textCurve[p].curve.rad);
ctx.fillText(ribbon[i], 0, 0);
ctx.restore();
x1 = ctx.measureText(ribbon[i]).width + letterPadding;
x2 = 0;
for (j = p; j < curveSample; j++) {
x2 = x2 + textCurve[j].curve.dist;
if (x2 >= x1) {
p = j;
break;
}
}
}
} //end FillRibon
function bezier(b1, b2) {
//Final stage which takes p, p+1 and calculates the rotation, distance on the path and accumulates the total distance
this.rad = Math.atan(b1.point.mY / b1.point.mX);
this.b2 = b2;
this.b1 = b1;
dx = (b2.x - b1.x);
dx2 = (b2.x - b1.x) * (b2.x - b1.x);
this.dist = Math.sqrt(((b2.x - b1.x) * (b2.x - b1.x)) + ((b2.y - b1.y) * (b2.y - b1.y)));
xDist = xDist + this.dist;
this.curve = {
rad: this.rad,
dist: this.dist,
cDist: xDist
};
}
function bezierT(t, startX, startY, control1X, control1Y, control2X, control2Y, endX, endY) {
//calculates the tangent line to a point in the curve; later used to calculate the degrees of rotation at this point.
this.mx = (3 * (1 - t) * (1 - t) * (control1X - startX)) + ((6 * (1 - t) * t) * (control2X - control1X)) + (3 * t * t * (endX - control2X));
this.my = (3 * (1 - t) * (1 - t) * (control1Y - startY)) + ((6 * (1 - t) * t) * (control2Y - control1Y)) + (3 * t * t * (endY - control2Y));
}
function bezier2(t, startX, startY, control1X, control1Y, control2X, control2Y, endX, endY) {
//Quadratic bezier curve plotter
this.Bezier1 = new bezier1(t, startX, startY, control1X, control1Y, control2X, control2Y);
this.Bezier2 = new bezier1(t, control1X, control1Y, control2X, control2Y, endX, endY);
this.x = ((1 - t) * this.Bezier1.x) + (t * this.Bezier2.x);
this.y = ((1 - t) * this.Bezier1.y) + (t * this.Bezier2.y);
this.slope = new bezierT(t, startX, startY, control1X, control1Y, control2X, control2Y, endX, endY);
this.point = {
t: t,
x: this.x,
y: this.y,
mX: this.slope.mx,
mY: this.slope.my
};
}
function bezier1(t, startX, startY, control1X, control1Y, control2X, control2Y) {
//linear bezier curve plotter; used recursivly in the quadratic bezier curve calculation
this.x = ((1 - t) * (1 - t) * startX) + (2 * (1 - t) * t * control1X) + (t * t * control2X);
this.y = ((1 - t) * (1 - t) * startY) + (2 * (1 - t) * t * control1Y) + (t * t * control2Y);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<TR>
<TH>Bezier Curve</TH>
<TD>
<input size="80" type="text" id="curve" name="curve" value="99.2,177.2,130.02,60.0,300.5,276.2,300.7,176.2">
</TD>
</TR>
<TR>
<TH>Text</TH>
<TD>
<input size="80" type="text" id="text" name="text" value="testing 1234567890">
</TD>
</TR>
<TR>
<TD colspan=2>
<div id="canvasDiv"></div>
</TD>
</TR>
</table>
An old old question... nevertheless, on my blog, I take a fairly close look at creating circular text using HTML5 Canvas:
html5graphics.blogspot.com
In the example, options include rounded text alignment (left, center and right) from a given angle, inward and outward facing text, kerning (adjustable gap between characters) and text inside or outside the radius.
There is also a jsfiddle with a working example.
It is as follows:
document.body.appendChild(getCircularText("ROUNDED TEXT LOOKS BEST IN CAPS!", 250, 0, "center", true, true, "Arial", "18pt", 0));
function getCircularText(text, diameter, startAngle, align, textInside, inwardFacing, fName, fSize, kerning) {
// text: The text to be displayed in circular fashion
// diameter: The diameter of the circle around which the text will
// be displayed (inside or outside)
// startAngle: In degrees, Where the text will be shown. 0 degrees
// if the top of the circle
// align: Positions text to left right or center of startAngle
// textInside: true to show inside the diameter. False draws outside
// inwardFacing: true for base of text facing inward. false for outward
// fName: name of font family. Make sure it is loaded
// fSize: size of font family. Don't forget to include units
// kearning: 0 for normal gap between letters. positive or
// negative number to expand/compact gap in pixels
//------------------------------------------------------------------------
// declare and intialize canvas, reference, and useful variables
align = align.toLowerCase();
var mainCanvas = document.createElement('canvas');
var ctxRef = mainCanvas.getContext('2d');
var clockwise = align == "right" ? 1 : -1; // draw clockwise for aligned right. Else Anticlockwise
startAngle = startAngle * (Math.PI / 180); // convert to radians
// calculate height of the font. Many ways to do this
// you can replace with your own!
var div = document.createElement("div");
div.innerHTML = text;
div.style.position = 'absolute';
div.style.top = '-10000px';
div.style.left = '-10000px';
div.style.fontFamily = fName;
div.style.fontSize = fSize;
document.body.appendChild(div);
var textHeight = div.offsetHeight;
document.body.removeChild(div);
// in cases where we are drawing outside diameter,
// expand diameter to handle it
if (!textInside) diameter += textHeight * 2;
mainCanvas.width = diameter;
mainCanvas.height = diameter;
// omit next line for transparent background
mainCanvas.style.backgroundColor = 'lightgray';
ctxRef.font = fSize + ' ' + fName;
// Reverse letter order for align Left inward, align right outward
// and align center inward.
if (((["left", "center"].indexOf(align) > -1) && inwardFacing) || (align == "right" && !inwardFacing)) text = text.split("").reverse().join("");
// Setup letters and positioning
ctxRef.translate(diameter / 2, diameter / 2); // Move to center
startAngle += (Math.PI * !inwardFacing); // Rotate 180 if outward
ctxRef.textBaseline = 'middle'; // Ensure we draw in exact center
ctxRef.textAlign = 'center'; // Ensure we draw in exact center
// rotate 50% of total angle for center alignment
if (align == "center") {
for (var j = 0; j < text.length; j++) {
var charWid = ctxRef.measureText(text[j]).width;
startAngle += ((charWid + (j == text.length-1 ? 0 : kerning)) / (diameter / 2 - textHeight)) / 2 * -clockwise;
}
}
// Phew... now rotate into final start position
ctxRef.rotate(startAngle);
// Now for the fun bit: draw, rotate, and repeat
for (var j = 0; j < text.length; j++) {
var charWid = ctxRef.measureText(text[j]).width; // half letter
ctxRef.rotate((charWid/2) / (diameter / 2 - textHeight) * clockwise); // rotate half letter
// draw char at "top" if inward facing or "bottom" if outward
ctxRef.fillText(text[j], 0, (inwardFacing ? 1 : -1) * (0 - diameter / 2 + textHeight / 2));
ctxRef.rotate((charWid/2 + kerning) / (diameter / 2 - textHeight) * clockwise); // rotate half letter
}
// Return it
return (mainCanvas);
}
You can try the following code to see how to write text along an Arc Path using HTML5 Canvas
function drawTextAlongArc(context, str, centerX, centerY, radius, angle) {
var len = str.length,
s;
context.save();
context.translate(centerX, centerY);
context.rotate(-1 * angle / 2);
context.rotate(-1 * (angle / len) / 2);
for (var n = 0; n < len; n++) {
context.rotate(angle / len);
context.save();
context.translate(0, -1 * radius);
s = str[n];
context.fillText(s, 0, 0);
context.restore();
}
context.restore();
}
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),
centerX = canvas.width / 2,
centerY = canvas.height - 30,
angle = Math.PI * 0.8,
radius = 150;
context.font = '30pt Calibri';
context.textAlign = 'center';
context.fillStyle = 'blue';
context.strokeStyle = 'blue';
context.lineWidth = 4;
drawTextAlongArc(context, 'Text along arc path', centerX, centerY, radius, angle);
// draw circle underneath text
context.arc(centerX, centerY, radius - 10, 0, 2 * Math.PI, false);
context.stroke();
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="250"></canvas>
</body>
</html>
You can't in any built in way. Please note that SVG natively does support text along paths, so you might want to consider SVG instead!
But you can write custom code in order to achieve the same effect, as some of us did for this question here: HTML5 Canvas Circle Text

Categories

Resources