Orthographic perspective map ̀problems - javascript

I was trying to make a sphere using some data I found on Wikipedia about the Orthographic projection of a map and there's been something that has been keeping me busy for some time. When I run the project, on the center of the sphere there apears one pixel that is colored in a wrong way when changing the longitude. I tried to solve this problem in a lot of ways like using ifs to separe the wrong pixel from the rest of them or delaying the longitude of the wrong pixel but neither of those worked, can somebody help me?
var Canvas = document.getElementById("MainCanvas");
Canvas.style.imageRendering = "pixelated";
var Context = Canvas.getContext("2d");
var Sphere = {
radius: 80,
lat: 0,
long: 0
}
Render();
function Render()
{
let ImgData = Context.createImageData(Canvas.width, Canvas.height);
//Sphere.lat += 0.02;
Sphere.long += 0.01;
document.getElementById("Display").innerHTML = Sphere.long;
for(var y = 0; y != Canvas.height; y++)
{
for(var x = 0; x != Canvas.width; x++)
{
/*Get the true position*/
let TrueX = x - Canvas.width / 2;
let TrueY = Canvas.height / 2 - y;
/*Get the distance*/
let Dist = Math.sqrt(TrueX * TrueX + TrueY * TrueY);
if(Dist < Sphere.radius)
{
let C, CurrLat, CurrLong;
/*Get the depth of a sphere point*/
C = Math.asin(Dist / Sphere.radius);
/*Color the pixel*/
if(TrueX === 0 && TrueY === 0)
{
CurrLong = (Sphere.long) % (Math.PI);
CurrLat = (Sphere.lat) % (2*Math.PI);
}
else
{
/*Get the latitude (Clamped the value to 0 → π)*/
CurrLong = (Math.asin(Math.cos(C)*Math.sin(Sphere.long)+(TrueY*Math.sin(C)*Math.cos(Sphere.long))/Dist)) % Math.PI;
/*And the longitude (Clamped the value to 0 → 2π)*/
CurrLat = (Sphere.lat + Math.atan2((TrueX*Math.sin(C)), (Dist*Math.cos(C)*Math.cos(Sphere.long) - (TrueY*Math.sin(C)*Math.sin(Sphere.long))))) % (2*Math.PI);
}
ImgData.data[4*((y * Canvas.width)+x)] = (CurrLong / (Math.PI)) * 255;
ImgData.data[4*((y * Canvas.width)+x)+1] = 0;
ImgData.data[4*((y * Canvas.width)+x)+2] = (CurrLat / (Math.PI * 2)) * 255;
ImgData.data[4*((y * Canvas.width)+x)+3] = 255;
}
else
{
ImgData.data[4*((y * Canvas.width)+x)] = 200;
ImgData.data[4*((y * Canvas.width)+x)+1] = 200;
ImgData.data[4*((y * Canvas.width)+x)+2] = 200;
ImgData.data[4*((y * Canvas.width)+x)+3] = 255;
}
}
}
Context.putImageData(ImgData, 0, 0);
requestAnimationFrame(Render);
}
#MainCanvas
{
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-image: url("https://c.tenor.com/k9yAts9ymaIAAAAM/loading-load.gif");
background-size: 100vw 100vh;
}
#Display
{
position: absolute;
top: 10px;
left: 10px;
z-index: 10;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="MainCanvas" width="400" height="200"></canvas>
<div id="Display"></div>
</body>
</html>

Ok, now I understand it. The value of longitude must be between -π/2 and π/2

Related

Fibonacci Sphere with svg(images) instead of points

I am trying to do a Fibonacci Sphere with a canvas like the following code, but instead of the same point showing everywhere I want to show different images, possibly svgs like logos and other images. I've done some research in google like visiting codepen and other places but couldn't find anything that worked. I imagine it would be something like the one in this website here. Any idea on how to approach this?
var cant = 100;
var offset = 2 / cant;
var increment = Math.PI * (3 - Math.sqrt(5));
var canvas = document.getElementById("canvas");
var i;
var circle;
//---Build the elements
for(i = 0; i < cant; i++){
circle = document.createElement("div");
circle.className = "point";
circle.setAttribute("data-index", i);
canvas.appendChild(circle);
};
//---Apply transformations to points
function updatePoints(evt){
var x, y, z, r, a, scale, opacity, point, style;
var angle = (evt) ? (-evt.pageX / 4) * Math.PI / 180 : 0;
for(i = 0; i < cant; i++){
y = (i * offset - 1) + (offset / 2);
r = Math.sqrt(1 - Math.pow(y, 2));
a = ((i + 1) % cant) * increment + angle;
x = Math.cos(a) * r;
z = Math.sin(a) * r;
scale = Math.round(z * 20000) / 100;
opacity = (1 + z) / 1.5;
style = "translate3d(" + (125 + x * 100) + "px, " + (125 + y * 100) + "px, " + scale + "px)";
point = canvas.querySelectorAll("[data-index='" + i +"']");
point[0].style.WebkitTransform = style;
point[0].style.msTransform = style;
point[0].style.transform = style;
point[0].style.opacity = opacity;
}
}
//---Update the points at start
updatePoints();
//---Update the points on mouse move
document.addEventListener("mousemove", updatePoints);
body, html{
height: 100%;
position: relative;
}
body{
background-color: #232B2B;
margin: 0;
padding: 0;
}
#canvas{
height: 250vh;
margin: 0 0;
position: relative;
width: 250vh;
}
.point{
background: red;
border-radius: 50%;
height: 4px;
position: absolute;
transform-style: preserve-3d;
width: 4px;
}
<div id="canvas">
</div>
Any help would be most helpful.
You can continue using the createElement method.
I added this, to show a random image (from picsum) for each dot:
// Create a new img element
img = document.createElement('img');
// Add the src to each img element.
//Here using the iterator variable to
//change the id of the photo we are retrieving
img.src = 'https://picsum.photos/id/' + i +'/20/20'
// Append the img to the div
circle.appendChild(img);
And I made the circles a bit larger in the CSS (20px) so you can see it.
If you want specific images, you could create an array inside your JS, or pull from a folder on your server.
var cant = 100;
var offset = 2 / cant;
var increment = Math.PI * (3 - Math.sqrt(5));
var canvas = document.getElementById("canvas");
var i;
var circle;
//---Build the elements
for(i = 0; i < cant; i++){
circle = document.createElement("div");
img = document.createElement('img');
img.src = 'https://picsum.photos/id/' + i +'/20/20'
circle.appendChild(img);
circle.className = "point";
circle.setAttribute("data-index", i);
canvas.appendChild(circle);
};
//---Apply transformations to points
function updatePoints(evt){
var x, y, z, r, a, scale, opacity, point, style;
var angle = (evt) ? (-evt.pageX / 4) * Math.PI / 180 : 0;
for(i = 0; i < cant; i++){
y = (i * offset - 1) + (offset / 2);
r = Math.sqrt(1 - Math.pow(y, 2));
a = ((i + 1) % cant) * increment + angle;
x = Math.cos(a) * r;
z = Math.sin(a) * r;
scale = Math.round(z * 20000) / 100;
opacity = (1 + z) / 1.5;
style = "translate3d(" + (125 + x * 100) + "px, " + (125 + y * 100) + "px, " + scale + "px)";
point = canvas.querySelectorAll("[data-index='" + i +"']");
point[0].style.WebkitTransform = style;
point[0].style.msTransform = style;
point[0].style.transform = style;
point[0].style.opacity = opacity;
}
}
//---Update the points at start
updatePoints();
//---Update the points on mouse move
document.addEventListener("mousemove", updatePoints);
body, html{
height: 100%;
position: relative;
}
body{
background-color: #232B2B;
margin: 0;
padding: 0;
}
#canvas{
height: 250vh;
margin: 0 0;
position: relative;
width: 250vh;
}
.point{
background: red;
border-radius: 50%;
height: 20px;
position: absolute;
transform-style: preserve-3d;
width: 20px;
overflow: hidden;
}
<div id="canvas">
</div>

Alternative to element.getBoundingClientRect()

I have been using getBoundingClientRect(). At the beginning, I'm getting performance issues due to this. If I remove this method from my code, there is working well. Any alternatives to getBoundingClientRect() in javascript.
In this sample, I have created 2000 elements in button click and changed their positions in another button click. In that, I'm getting performance issues when using getBoundingClientRect().
Anyone help me to resolve this.
document.getElementById("click1").onclick = function() {
for (var i = 0; i < 2000; i++) {
var ele = document.createElement("DIV");
ele.id = i + '';
ele.className = "square";
ele.setAttribute("style", "position: absolute;left: 200px; top: 100px");
document.getElementById("marker").appendChild(ele);
}
};
document.getElementById("click").onclick = function() {
var markerCollection = document.getElementById("marker");
var width = 20,
height = 20;
var radius = width * 2;
var area = 2 * 3.14 * radius;
var totalMarker = 0;
var numberOfMarker = Math.round(area / width);
totalMarker += numberOfMarker;
var percent = Math.round((height / area) * 100);
percent =
markerCollection.children.length - 1 < numberOfMarker ?
100 / markerCollection.children.length - 1 :
percent;
var angle = (percent / 100) * 360;
var centerX = 200,
centerY = 100;
var count = 1;
var newAngle = 0,
first = false;
var dt1 = 0,
dt2 = 0;
dt1 = new Date().getTime();
for (var i = 0; i < markerCollection.children.length; i++) {
if (i != 1 && (i - 1) % totalMarker === 0) {
count++;
radius = (width + 10) * count;
newAngle = 0;
area = 2 * 3.14 * radius;
numberOfMarker = Math.round(area / width);
percent = Math.round((height / area) * 100);
angle = (percent / 100) * 360;
totalMarker += numberOfMarker;
}
var x1 = centerX + radius * Math.sin((Math.PI * 2 * newAngle) / 360);
var y1 = centerY + radius * Math.cos((Math.PI * 2 * newAngle) / 360);
var offset = markerCollection.children[i].getBoundingClientRect();
markerCollection.children[i]["style"].left = (x1 - (offset.width / 2)) + "px";
markerCollection.children[i]["style"].top = (y1 - (offset.height / 2)) + "px";
newAngle += angle;
}
dt2 = new Date().getTime();
alert(dt2 - dt1);
};
<!DOCTYPE html>
<html>
<head>
<style>
.square {
height: 20px;
width: 20px;
background-color: #555;
border: 1px solid red;
}
</style>
</head>
<body>
<button id="click1">Create Element</button>
<button id="click">Click To Change</button>
<div id='marker' style="width: 350px;height: 200px;border: 1px solid red">
</div>
</div>
<script>
</script>
</body>
</html>
If I'm not misreading your code, all you're using getBoundingClientRect() for is to calculate the width and height of an element you already know the width and height of (20x20px).
Just use your width and height variables directly, or possibly avoid having to do the offset calculation entirely, add transform: translate(-50% -50%) to the element's style.

How can i customize the lines of this canvas?

I started to work on this animation and got the base from another animation, i have pretty much customized it all to my needs besides the lines. Currently the lines are pointy and i have gone through the code multiple times trying to find what creates these spiky lines. I would appreciate if someone could check both the provided code and the external code and identify what it is. All help is appreciated thanks.
// Settings
var particleCount = 35,
flareCount = 0,
motion = 0.05,
tilt = 0,
particleSizeBase = 1,
particleSizeMultiplier = 0.5,
flareSizeBase = 100,
flareSizeMultiplier = 100,
glareAngle = -60,
glareOpacityMultiplier = 0.4,
renderParticles = true,
renderParticleGlare = true,
renderFlares = false,
renderLinks = false,
renderMesh = false,
flicker = false,
flickerSmoothing = 15, // higher = smoother flicker
blurSize = 0,
orbitTilt = true,
randomMotion = true,
noiseLength = 1000,
noiseStrength = 3;
document.querySelectorAll('.stars').forEach(canvas => {
var context = canvas.getContext('2d'),
color = canvas.dataset['color'],
mouse = { x: 0, y: 0 },
m = {},
r = 0,
c = 1000, // multiplier for delaunay points, since floats too small can mess up the algorithm
n = 0,
nAngle = (Math.PI * 2) / noiseLength,
nRad = 100,
nScale = 1,
nPos = {x: 0, y: 0},
points = [],
vertices = [],
triangles = [],
links = [],
particles = [],
flares = [];
function init() {
var i, j, k;
// requestAnimFrame polyfill
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
// Size canvas
resize();
mouse.x = canvas.clientWidth / 2;
mouse.y = canvas.clientHeight / 2;
// Create particle positions
for (i = 0; i < particleCount; i++) {
var p = new Particle();
particles.push(p);
points.push([p.x*c, p.y*c]);
}
vertices = Delaunay.triangulate(points);
var tri = [];
for (i = 0; i < vertices.length; i++) {
if (tri.length == 2) {
triangles.push(tri);
tri = [];
}
tri.push(vertices[i]);
}
// Tell all the particles who their neighbors are
for (i = 0; i < particles.length; i++) {
// Loop through all tirangles
for (j = 0; j < triangles.length; j++) {
// Check if this particle's index is in this triangle
k = triangles[j].indexOf(i);
// If it is, add its neighbors to the particles contacts list
if (k !== -1) {
triangles[j].forEach(function(value, index, array) {
if (value !== i && particles[i].neighbors.indexOf(value) == -1) {
particles[i].neighbors.push(value);
}
});
}
}
}
var fps = 60;
var now;
var then = Date.now();
var interval = 1000/fps;
var delta;
// Animation loop
(function animloop(){
requestAnimFrame(animloop);
now = Date.now();
delta = now - then;
if (delta > interval) {
then = now - (delta % interval);
resize();
render();
}
})();
}
function render() {
if (randomMotion) {
n++;
if (n >= noiseLength) {
n = 0;
}
nPos = noisePoint(n);
}
if (renderParticles) {
// Render particles
for (var i = 0; i < particleCount; i++) {
particles[i].render();
}
}
}
function resize() {
canvas.width = window.innerWidth * (window.devicePixelRatio || 1);
canvas.height = canvas.width * (canvas.clientHeight / canvas.clientWidth);
}
// Particle class
var Particle = function() {
this.x = random(-0.1, 1.1, true);
this.y = random(-0.1, 1.1, true);
this.z = random(0,4);
this.color = color;
this.opacity = random(0.1,1,true);
this.flicker = 0;
this.neighbors = []; // placeholder for neighbors
};
Particle.prototype.render = function() {
var pos = position(this.x, this.y, this.z),
r = ((this.z * particleSizeMultiplier) + particleSizeBase) * (sizeRatio() / 1000),
o = this.opacity;
context.fillStyle = this.color;
context.globalAlpha = o;
context.beginPath();
context.fill();
context.closePath();
if (renderParticleGlare) {
context.globalAlpha = o * glareOpacityMultiplier;
context.ellipse(pos.x, pos.y, r * 100, r, (glareAngle - ((nPos.x - 0.5) * noiseStrength * motion)) * (Math.PI / 180), 0, 2 * Math.PI, false);
context.fill();
context.closePath();
}
context.globalAlpha = 1;
};
// Utils
function noisePoint(i) {
var a = nAngle * i,
cosA = Math.cos(a),
sinA = Math.sin(a),
rad = nRad;
return {
x: rad * cosA,
y: rad * sinA
};
}
function position(x, y, z) {
return {
x: (x * canvas.width) + ((((canvas.width / 2) - mouse.x + ((nPos.x - 0.5) * noiseStrength)) * z) * motion),
y: (y * canvas.height) + ((((canvas.height / 2) - mouse.y + ((nPos.y - 0.5) * noiseStrength)) * z) * motion)
};
}
function sizeRatio() {
return canvas.width >= canvas.height ? canvas.width : canvas.height;
}
function random(min, max, float) {
return float ?
Math.random() * (max - min) + min :
Math.floor(Math.random() * (max - min + 1)) + min;
}
// init
if (canvas) init();
});
html,
body {
margin: 0;
padding: 0;
height: 100%;
}
body {
background: #000;
background-image: linear-gradient(-180deg, rgba(0, 0, 0, 0.00) 0%, #000000 100%);
height: 100%;
}
#stars {
display: block;
position: relative;
width: 100%;
height: 100vh;
z-index: 1;
position: absolute;
}
<script src="https://rawgit.com/ironwallaby/delaunay/master/delaunay.js"></script>
<script src="http://requirejs.org/docs/release/2.1.15/minified/require.js"></script>
<canvas id="Stars" class="stars" width="300" height="300" data-color="#fff"></canvas>
// Tell all the particles who their neighbors are
for (i = 0; i < particles.length; i++) {
// Loop through all tirangles
for (j = 0; j < triangles.length; j++) {
// Check if this particle's index is in this triangle
k = triangles[j].indexOf(i);
// If it is, add its neighbors to the particles contacts list
if (k !== -1) {
triangles[j].forEach(function(value, index, array) { // <----- missing ')' here
if (value !== i && particles[i].neighbors.indexOf(value) == -1) {
particles[i].neighbors.push(value);
}
});
}
}
}
The reason you are getting spikes is the radius of the ellipse is too large so the ends are so small they look like points but it's just a small radius.
context.ellipse(pos.x, pos.y, r * 100, r, (glareAngle - ((nPos.x - 0.5) * noiseStrength * motion)) * (Math.PI / 180), 0, 2 * Math.PI, false);
After experimenting with different shapes like rect() and arc():
The code below instead of using ellipse uses a rotated rectangle. Since the shape is different the algorithm for getting the angle you wanted will need more work but this code solves the problem of the pointy ends.
//context.ellipse(pos.x, pos.y, r * 100, r, (glareAngle - ((nPos.x - 0.5) * noiseStrength * motion)) * (Math.PI / 180), 0, 2 * Math.PI, false);
context.rotate((glareAngle - ((nPos.x - 0.5) * noiseStrength * motion)) * (Math.PI / 180));
context.fillRect(pos.x, pos.y, r * 100, r)
context.closePath();
It will take more work to align them to match the first code, but the pointy ends are gone.
Also, rotate() is actually rotating the canvas not the rectangles so keep that in mind. I would start with a simple 45 degree angle and see what that generates.

Issue with high cpu usage with canvas and requestAnimationFrame

I found a canvas animation with requestAnimationFrame that im trying to change to my needs and i had a huge issue with cpu usage.. going up to 80% and i started to shave off things i dont want or need. Im down to 40-50% cpu usage now so i would like some help with what i could do to optimize this code and reduce the cpu usage.
I have read about requestAnimationFrame and that it runs at 60fps or even as high as possible and mabye that has a big part in the performance, perhaps there is something i could do there?
/**
* Stars
* Inspired by Steve Courtney's poster art for Celsius GS's Drifter - http://celsiusgs.com/drifter/posters.php
* by Cory Hughart - http://coryhughart.com
*/
// Settings
var particleCount = 40,
flareCount = 0,
motion = 0.05,
tilt = 0.05,
color = '#00FF7B',
particleSizeBase = 1,
particleSizeMultiplier = 0.5,
flareSizeBase = 100,
flareSizeMultiplier = 100,
lineWidth = 1,
linkChance = 75, // chance per frame of link, higher = smaller chance
linkLengthMin = 5, // min linked vertices
linkLengthMax = 7, // max linked vertices
linkOpacity = 0.25; // number between 0 & 1
linkFade = 90, // link fade-out frames
linkSpeed = 0, // distance a link travels in 1 frame
glareAngle = -60,
glareOpacityMultiplier = 0.05,
renderParticles = true,
renderParticleGlare = true,
renderFlares = false,
renderLinks = false,
renderMesh = false,
flicker = false,
flickerSmoothing = 15, // higher = smoother flicker
blurSize = 0,
orbitTilt = true,
randomMotion = true,
noiseLength = 1000,
noiseStrength = 1;
var canvas = document.getElementById('stars'),
context = canvas.getContext('2d'),
mouse = { x: 0, y: 0 },
m = {},
r = 0,
c = 1000, // multiplier for delaunay points, since floats too small can mess up the algorithm
n = 0,
nAngle = (Math.PI * 2) / noiseLength,
nRad = 100,
nScale = 0.5,
nPos = {x: 0, y: 0},
points = [],
vertices = [],
triangles = [],
links = [],
particles = [],
flares = [];
function init() {
var i, j, k;
// requestAnimFrame polyfill
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
};
})();
// Size canvas
resize();
mouse.x = canvas.clientWidth / 2;
mouse.y = canvas.clientHeight / 2;
// Create particle positions
for (i = 0; i < particleCount; i++) {
var p = new Particle();
particles.push(p);
points.push([p.x*c, p.y*c]);
}
vertices = Delaunay.triangulate(points);
var tri = [];
for (i = 0; i < vertices.length; i++) {
if (tri.length == 3) {
triangles.push(tri);
tri = [];
}
tri.push(vertices[i]);
}
// Tell all the particles who their neighbors are
for (i = 0; i < particles.length; i++) {
// Loop through all tirangles
for (j = 0; j < triangles.length; j++) {
// Check if this particle's index is in this triangle
k = triangles[j].indexOf(i);
// If it is, add its neighbors to the particles contacts list
if (k !== -1) {
triangles[j].forEach(function(value, index, array) {
if (value !== i && particles[i].neighbors.indexOf(value) == -1) {
particles[i].neighbors.push(value);
}
});
}
}
}
// Animation loop
(function animloop(){
requestAnimFrame(animloop);
resize();
render();
})();
}
function render() {
if (randomMotion) {
n++;
if (n >= noiseLength) {
n = 0;
}
nPos = noisePoint(n);
}
if (renderParticles) {
// Render particles
for (var i = 0; i < particleCount; i++) {
particles[i].render();
}
}
}
function resize() {
canvas.width = window.innerWidth * (window.devicePixelRatio || 1);
canvas.height = canvas.width * (canvas.clientHeight / canvas.clientWidth);
}
// Particle class
var Particle = function() {
this.x = random(-0.1, 1.1, true);
this.y = random(-0.1, 1.1, true);
this.z = random(0,4);
this.color = color;
this.opacity = random(0.1,1,true);
this.flicker = 0;
this.neighbors = []; // placeholder for neighbors
};
Particle.prototype.render = function() {
var pos = position(this.x, this.y, this.z),
r = ((this.z * particleSizeMultiplier) + particleSizeBase) * (sizeRatio() / 1000),
o = this.opacity;
context.fillStyle = this.color;
context.globalAlpha = o;
context.beginPath();
context.fill();
context.closePath();
if (renderParticleGlare) {
context.globalAlpha = o * glareOpacityMultiplier;
context.ellipse(pos.x, pos.y, r * 100, r, (glareAngle - ((nPos.x - 0.5) * noiseStrength * motion)) * (Math.PI / 180), 0, 2 * Math.PI, false);
context.fill();
context.closePath();
}
context.globalAlpha = 1;
};
// Flare class
// Link class
var Link = function(startVertex, numPoints) {
this.length = numPoints;
this.verts = [startVertex];
this.stage = 0;
this.linked = [startVertex];
this.distances = [];
this.traveled = 0;
this.fade = 0;
this.finished = false;
};
// Utils
function noisePoint(i) {
var a = nAngle * i,
cosA = Math.cos(a),
sinA = Math.sin(a),
rad = nRad;
return {
x: rad * cosA,
y: rad * sinA
};
}
function position(x, y, z) {
return {
x: (x * canvas.width) + ((((canvas.width / 2) - mouse.x + ((nPos.x - 0.5) * noiseStrength)) * z) * motion),
y: (y * canvas.height) + ((((canvas.height / 2) - mouse.y + ((nPos.y - 0.5) * noiseStrength)) * z) * motion)
};
}
function sizeRatio() {
return canvas.width >= canvas.height ? canvas.width : canvas.height;
}
function random(min, max, float) {
return float ?
Math.random() * (max - min) + min :
Math.floor(Math.random() * (max - min + 1)) + min;
}
// init
if (canvas) init();
html,
body {
margin: 0;
padding: 0;
height: 100%;
}
body {
background: #375848;
background-image: linear-gradient(-180deg, rgba(0,0,0,0.00) 0%, #000000 100%);
}
#stars {
display: block;
position: relative;
width: 100%;
height: 16rem;
height: 100vh;
z-index: 1;
position: absolute;
}
<script src="https://rawgit.com/ironwallaby/delaunay/master/delaunay.js"></script>
<script src="http://requirejs.org/docs/release/2.1.15/minified/require.js"></script>
<canvas id="stars" width="300" height="300"></canvas>
I had two things to suggest, one of which someone already mentioned in a comment -- only resize your canvas on resize events.
The other was to compare the time of each call to your animation loop with the time of the last call, and only render again if a certain amount of time has passed -- say 16 milliseconds for about a 60 fps rate.
var lastRender = 0;
(function animloop(){
requestAnimFrame(animloop);
var now = Date.now();
if (now >= lastRender + 16) {
render();
lastRender = now;
}
})();

changing image color while animating it in javascript

I have an image drawn on a canvas. The image for now is doing a simple circular rotation on each frame.
The image scaling is based on the value entered in the text box.
I put the jsfiddle as suggested below
var canvas = null;
var ctx = null;
var image = null;
var slider = null;
var vBox = null;
var x = 50;
var y = 50;
var scaleX;
var scaleY;
var center = {
x: 0,
y: 0
};
var radius = 50.0;
var angle = 0;
var result = false;
var textActive = false;
var imgArr = null;
var imageData;
var data;
function start() {
ctx = getCtxReference();
image = getImageReference();
result = setOtherReferences();
imgArr = getStarImages();
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
for (var i = 0; i < imgArr.length; i++) {
imgArr[i].addEventListener('load', drawBackgroundStar)
}
if (image != null && result && imgArr != null) {
Loop();
}
}
function checkKeyPressed(e) {
if (e.keyCode == "65") {
changeImgColorToBlue();
}
}
function getCtxReference() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
return ctx;
}
function getImageReference() {
image = new Image();
image.src = "star.png";
image.addEventListener('load', drawImg);
return image;
}
function setOtherReferences() {
slider = document.getElementById("rangeInput");
vBox = document.getElementById("textbox");
scaleX = 100;
scaleY = 100;
center.x = canvas.width / 3;
center.y = canvas.height / 3;
return true;
}
function getStarImages() {
var arr = new Array();
for (var i = 0; i < 500; i++) {
var img = new Image();
img.src = "star.png";
arr.push(img);
}
return arr;
}
function drawImg() {
ctx.drawImage(image, x, y, scaleX, scaleY);
return true;
}
function drawBackgroundStar() {
for (var i = 0; i < imgArr.length; i++) {
ctx.drawImage(imgArr[i], getRandomArbitrary(0, canvas.width), getRandomArbitrary(0, canvas.height), getRandomArbitrary(5, 15), getRandomArbitrary(5, 15));
}
}
function Loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
window.setTimeout(Loop, 100);
angle += Math.PI * 0.05;
x = center.x + radius * Math.cos(angle);
y = center.y + radius * Math.sin(angle);
vBox.value = slider.value;
updateStarScale();
drawImg();
//drawBackgroundStar();
}
function updateStarScale() {
if (vBox.value > 0) {
scaleX += vBox.value / 10;
scaleY += vBox.value / 10;
changeImgColorToBlue();
} else if (vBox.value < 0) {
scaleX -= Math.abs(vBox.value / 10);
scaleY -= Math.abs(vBox.value / 10);
changeImgColorToRed();
}
if (scaleX > 600 || scaleY > 600) {
scaleX = 600;
scaleY = 600;
} else if (scaleX < 50 || scaleY < 50) {
scaleX = 50;
scaleY = 50;
}
}
function changeImgColorToBlue() {
for (var i = 0; i < data.length; i += 4) {
data[i] = 0; // red
data[i + 1] = 0; // green
data[i + 2] = 255; // blue
}
ctx.putImageData(imageData, 0, 0);
}
function changeImgColorToRed() {
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
<html>
<style type="text/css">
body {
text-align: center;
background-image: url("stars.png");
}
#container {
position: fixed;
color: red;
top: 0px;
left: 0px;
}
#textBox {
position: absolute;
top: 25px;
left: 5px;
}
#slider {
position: absolute;
top: 25px;
left: 200px;
}
</style>
<body onload="start()">
<canvas id="canvas" width="1024" height="768"></canvas>
<div id="container">
<div id="textBox">
Velocity:
<input type="text" id="textbox" value="0">
</div>
<div id="slider">
Slider:
<form oninput="amount.value=rangeInput.value">
<input type="range" id="rangeInput" name="rangeInput" min="-100" max="100" step="3" value="">
<output name="amount" for="rangeInput">0</output>
</form>
</div>
</div>
<script type="text/javascript" src="main.js">
</script>
</body>
</html>
So in my Loop(), I am updating the position of my image. In the updateStarScale() I am scaling the image size based on the value given in the text box by the user. All of this works fine. My only concern is the changeImgColorToBlue() which does nothing to the image color. I want the image color to be changed to blue but this doesn't work. What am I doing wrong?
**
UPDATE 1.0:
**
After suggestions from the last post, I changed the code to below. There are two yellow stars on the screen now and they scale up based on the sliders but alongside scaling I want their colors to change ie when they are scaled up they turn blue and when they are scaled down they turn red but the colors don't change.
//Create the images(Using a canvas for CORS issues)
function createStars() {
var imgCanvas = document.createElement('canvas');
imgCanvas.height = "500";
imgCanvas.width = "500";
var imgCtx = imgCanvas.getContext('2d');
imgCtx.fillStyle = 'black';
imgCtx.fillRect(0, 0, 500, 500)
imgCtx.fillStyle = '#FF0';
for (i = 0; i < Math.floor(Math.random() * 500) + 250; i++) {
imgCtx.fillRect(Math.random() * 500, Math.random() * 500, 1, 1)
}
document.body.style.backgroundImage = 'url(' + imgCanvas.toDataURL() + ')';
}
createStars();
var canvas = null;
var ctx = null;
var image = null;
var slider = null;
var vBox = null;
var x = 50;
var y = 50;
var scaleX;
var scaleY;
var center = {
x: 0,
y: 0
};
var radius = 50.0;
var angle = 0;
var result = false;
var imageData;
var data;
var backgroundImg = null;
function start() {
ctx = getCtxReference();
result = setOtherReferences();
image = getStarImages();
if (image != null)
image.addEventListener('load', Loop);
}
function getCtxReference() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
return ctx;
}
function setOtherReferences() {
slider = document.getElementById("rangeInput");
vBox = document.getElementById("textbox");
scaleX = 150;
scaleY = 150;
center.x = canvas.width / 3;
center.y = canvas.height / 3;
return true;
}
function getStarImages() {
var img = new Image();
img.src = createStar();
return img;
}
function createStar() {
ctx.fillStyle = '#FF0';
ctx.fillRect(Math.random() * 45, Math.random() * 45, scaleX, scaleY);
return canvas.toDataURL();
}
function drawImg() {
ctx.drawImage(image, x, y, scaleX, scaleY);
}
function Loop() {
window.setTimeout(Loop, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
angle += Math.PI * 0.05;
x = center.x + radius * Math.cos(angle);
y = center.y + radius * Math.sin(angle);
vBox.value = slider.value;
updateStarScale();
drawImg();
}
function updateStarScale() {
if (vBox.value > 0) {
scaleX += vBox.value / 10;
scaleY += vBox.value / 10;
changeImgColorToBlue();
} else if (vBox.value < 0) {
scaleX -= Math.abs(vBox.value / 10);
scaleY -= Math.abs(vBox.value / 10);
changeImgColorToRed();
}
if (scaleX > 600 || scaleY > 600) {
scaleX = 600;
scaleY = 600;
} else if (scaleX < 50 || scaleY < 50) {
scaleX = 50;
scaleY = 50;
}
}
function changeImgColorToBlue() {
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
//is our data black?
if (data[i] > 0 || data[i + 1] > 0 || data[i + 2] > 0) {
data[i] = 0; // red
data[i + 1] = 0; // green
data[i + 2] = 255; // blue
}
}
ctx.putImageData(imageData, 0, 0);
}
function changeImgColorToRed() {
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
if (data[i] > 0 || data[i + 1] > 0 || data[i + 2] > 0) {
data[i] = 255; // red
data[i + 1] = 0; // green
data[i + 2] = 0; // blue
}
}
ctx.putImageData(imageData, 0, 0);
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
start();
Edit
Ok, so if you only need to draw those moving stars, you can simplify a lot your code, especially about the changing color :
As each star is only a colored rectangle, you only have to store a color value (i.e hex) and update it when you want to the desired color. No bitmap calculation needed.
However, as your code is right now, if you try to create new stars, they will all follow the same path and scale update.
I think that you will have to rethink the way you update the position.
Here is an update, with simplification of the code and example showing the issue
function createStars() {
var imgCanvas = document.createElement('canvas');
imgCanvas.height = "500";
imgCanvas.width = "500";
var imgCtx = imgCanvas.getContext('2d');
imgCtx.fillStyle = 'black';
imgCtx.fillRect(0, 0, 500, 500)
imgCtx.fillStyle = '#FF0';
for (i = 0; i < Math.floor(Math.random() * 500) + 250; i++) {
imgCtx.fillRect(Math.random() * 500, Math.random() * 500, 1, 1)
}
document.body.style.backgroundImage = 'url(' + imgCanvas.toDataURL() + ')';
}
createStars();
var canvas = null;
var ctx = null;
var slider = null;
var vBox = null;
var x = 50;
var y = 50;
var center = {
x: 0,
y: 0
};
var radius = 50.0;
var angle = 0;
var result = false;
var color = "FF0"; // set the color as a global variable, avoiding a function to set it
var stars = []; // set an array that will contain all our moving stars
function start() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
result = setOtherReferences();
// append new stars to our array
stars.push(createStar());
stars.push(createStar());
stars.push(createStar());
// start the Loop()
Loop();
}
function setOtherReferences() {
slider = document.getElementById("rangeInput");
vBox = document.getElementById("textbox");
center.x = canvas.width / 3;
center.y = canvas.height / 3;
return true;
}
function createStar() {
// set moving stars as object, with their own x,y,width and height properties.
var star = {
xStart: Math.random() * 150, // used in order to avoid the exact
yStart: Math.random() * 150, // same position of your stars
x: this.xStart,
y: this.yStart,
w: 50,
h: 50
}
return star;
}
function drawImg() {
// set the moving stars color to the actual growing/shrinking state
ctx.fillStyle = color;
// for each of our moving stars, draw a rect
for (i = 0; i < stars.length; i++) {
ctx.fillRect(stars[i].x, stars[i].y, stars[i].w, stars[i].h);
}
}
function Loop() {
window.setTimeout(Loop, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
angle += Math.PI * 0.05;
/*
Here is the main issue
as each of our stars x/y pos are updated with the same function,
they will follow each others.
I added the xStart property so they're not
exactly at the same position for you beeing able to see it.
*/
for (i = 0; i < stars.length; i++) {
stars[i].x = center.x + radius * Math.cos(angle) + stars[i].xStart;
stars[i].y = center.y + radius * Math.sin(angle) + stars[i].yStart;
}
vBox.value = slider.value;
updateStarScale();
drawImg();
}
function updateStarScale() {
//same as above, each of our stars will have the same scale update
for (i = 0; i < stars.length; i++) {
if (vBox.value > 0) {
stars[i].w += vBox.value / 10;
stars[i].h += vBox.value / 10;
color = "#00F";
} else if (vBox.value < 0) {
stars[i].w -= Math.abs(vBox.value / 10);
stars[i].h -= Math.abs(vBox.value / 10);
color = "#F00";
}
if (stars[i].w > 600 || stars[i].h > 600) {
stars[i].w = 600;
stars[i].h = 600;
} else if (stars[i].w < 5 || stars[i].h < 5) {
stars[i].w = 5;
stars[i].h = 5;
}
}
}
// Only call it if you haven't already done (i.e in a load event)
start();
body {
text-align: center;
background-image: url("stars.png");
}
#container {
position: fixed;
color: red;
top: 0px;
left: 0px;
}
#textBox {
position: absolute;
top: 25px;
left: 5px;
}
#slider {
position: absolute;
top: 25px;
left: 200px;
}
<canvas id="canvas" width="1024" height="768"></canvas>
<div id="container">
<div id="textBox">
Velocity:
<input type="text" id="textbox" value="0">
</div>
<div id="slider">
Slider:
<form oninput="amount.value=rangeInput.value">
<input type="range" id="rangeInput" name="rangeInput" min="-100" max="100" step="3" value="0">
<output name="amount" for="rangeInput">0</output>
</form>
</div>
</div>
Original answer
First, You will need to update your imageData each time you call changeImgColorToBlue.
Secondly, in order to not change all your pixels into blue, you will have to check if each pixel is in some range of color.
Assuming your star.png does look like a black background with colored dots over it, you can do:
for (var i = 0; i < data.length; i += 4) {
if( data[i]>0 || data[i+1]>0 || data[i+2]>0 ){
//is our pixel black?
data[i] = 0;// red
data[i + 1] = 0; // green
data[i + 2] = 255; // blue
}
}
Of course, you can change those conditions to match for the actual color of your dots with more precision by using e.g if your dots are yellow
if( data[i]>=200 && data[i+1]>=200 && data[i+2]<100 )
Also, I did some changes in your code as you had redundant calls to some functions.
//Create the images(Using a canvas for CORS issues)
function createStars(){
var imgCanvas = document.createElement('canvas');
imgCanvas.height="500";
imgCanvas.width="500";
var imgCtx = imgCanvas.getContext('2d');
imgCtx.fillStyle= 'black';
imgCtx.fillRect(0,0,500,500)
imgCtx.fillStyle= '#FF0';
for(i=0; i<Math.floor(Math.random()*500)+250; i++){
imgCtx.fillRect(Math.random()*500, Math.random()*500, 1,1)
}
document.body.style.backgroundImage='url('+imgCanvas.toDataURL()+')';
}
createStars();
function createStar(){
var imgCanvas = document.createElement('canvas');
imgCanvas.height="50";
imgCanvas.width="50";
var imgCtx = imgCanvas.getContext('2d');
imgCtx.fillStyle= '#FF0';
imgCtx.fillRect(Math.random()*45,Math.random()*45, 5,5);
return imgCanvas.toDataURL();
}
var canvas = null;
var ctx = null;
var image = null;
var slider = null;
var vBox = null;
var x = 50;
var y = 50;
var scaleX;
var scaleY;
var center = {
x: 0,
y: 0
};
var radius = 50.0;
var angle = 0;
var result = false;
var textActive = false;
var imgArr = null;
var imageData;
var data;
var backgroundImg = null;
function start() {
ctx = getCtxReference();
result = setOtherReferences();
image = getStarImages();
if (image != null && result && imgArr != null) {
Loop();
}
}
function getCtxReference() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
return ctx;
}
function setOtherReferences() {
slider = document.getElementById("rangeInput");
vBox = document.getElementById("textbox");
scaleX = 100;
scaleY = 100;
center.x = canvas.width / 3;
center.y = canvas.height / 3;
return true;
}
function drawImg() {
ctx.drawImage(image, x, y, scaleX, scaleY);
return true;
}
function Loop() {
window.setTimeout(Loop, 100);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(backgroundImg, 0,0);
angle += Math.PI * 0.05;
x = center.x + radius * Math.cos(angle);
y = center.y + radius * Math.sin(angle);
vBox.value = slider.value;
updateStarScale();
drawImg();
}
function getStarImages() {
//as they're all the same image, you don't need to make an array of them, simply make a loop below
var img = new Image();
img.addEventListener('load', drawBackgroundStar)
img.src = createStar();
return img;
}
function drawBackgroundStar() {
for (var i=0; i<500; i++) {
ctx.drawImage(image, getRandomArbitrary(0, canvas.width), getRandomArbitrary(0, canvas.height), getRandomArbitrary(5, 15), getRandomArbitrary(5, 15));
}
backgroundImg = new Image();
backgroundImg.addEventListener('load', Loop);
backgroundImg.src = canvas.toDataURL();
}
function updateStarScale() {
if (vBox.value > 0) {
scaleX += vBox.value / 10;
scaleY += vBox.value / 10;
changeImgColorToBlue();
} else if (vBox.value < 0) {
scaleX -= Math.abs(vBox.value / 10);
scaleY -= Math.abs(vBox.value / 10);
changeImgColorToRed();
}
if (scaleX > 600 || scaleY > 600) {
scaleX = 600;
scaleY = 600;
} else if (scaleX < 50 || scaleY < 50) {
scaleX = 50;
scaleY = 50;
}
}
function changeImgColorToBlue() {
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
//is our data black?
if(data[i]>0||data[i+1]>0||data[i+2]>0){
data[i] = 0;// red
data[i + 1] = 0; // green
data[i + 2] = 255; // blue
}
}
ctx.putImageData(imageData, 0, 0);
}
function changeImgColorToRed() {
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
if(data[i]>0||data[i+1]>0||data[i+2]>0){
data[i] = 255;// red
data[i + 1] = 0; // green
data[i + 2] = 0; // blue
}
}
ctx.putImageData(imageData, 0, 0);
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
start();
body {
text-align: center;
}
#container {
position: fixed;
color: red;
top: 0px;
left: 0px;
}
#textBox {
position: absolute;
top: 25px;
left: 5px;
}
#slider {
position: absolute;
top: 25px;
left: 200px;
}
<canvas id="canvas" width="1024" height="768"></canvas>
<div id="container">
<div id="textBox">
Velocity:
<input type="text" id="textbox" value="0">
</div>
<div id="slider">
Slider:
<form oninput="amount.value=rangeInput.value">
<input type="range" id="rangeInput" name="rangeInput" min="-100" max="100" step="3" value="">
<output name="amount" for="rangeInput">0</output>
</form>
</div>
</div>
As you wrote it, the changeImgColorToBlue functions are only changing the background stars of your canvas. I'm not sure it is what you want to achieve so here is a way to only change this one dot :
function createStars(){
var imgCanvas = document.createElement('canvas');
imgCanvas.height="500";
imgCanvas.width="500";
var imgCtx = imgCanvas.getContext('2d');
imgCtx.fillStyle= 'black';
imgCtx.fillRect(0,0,500,500)
imgCtx.fillStyle= '#FF0';
for(i=0; i<Math.floor(Math.random()*500)+250; i++){
imgCtx.fillRect(Math.random()*500, Math.random()*500, 1,1)
}
document.body.style.backgroundImage='url('+imgCanvas.toDataURL()+')';
}
createStars();
function createStar(){
var imgCanvas = document.createElement('canvas');
imgCanvas.height="50";
imgCanvas.width="50";
var imgCtx = imgCanvas.getContext('2d');
imgCtx.fillStyle= '#FF0';
imgCtx.fillRect(Math.random()*45,Math.random()*45, 5,5);
return imgCanvas.toDataURL();
}
var canvas = null;
var ctx = null;
var starCanvas = null;
var starCtx = null;
var image = null;
var slider = null;
var vBox = null;
var x = 50;
var y = 50;
var scaleX;
var scaleY;
var center = {
x: 0,
y: 0
};
var radius = 50.0;
var angle = 0;
var result = false;
var textActive = false;
var imgArr = null;
var imageData;
var data;
var backgroundImg = null;
function start() {
ctx = getCtxReference();
starCtx = getStarReference();
result = setOtherReferences();
image = getStarImages();
if (image != null && result && imgArr != null && backgroundImg != null) {
Loop();
}
}
function getCtxReference() {
canvas = document.getElementById("canvas");
return canvas.getContext('2d');
}
function getStarReference() {
starCanvas = document.createElement("canvas");
starCanvas.height = 50;
starCanvas.width = 50;
starCanvas.id=('star');
document.body.appendChild(starCanvas);
return starCanvas.getContext('2d');
}
function setOtherReferences() {
slider = document.getElementById("rangeInput");
vBox = document.getElementById("textbox");
scaleX = 100;
scaleY = 100;
center.x = canvas.width / 3;
center.y = canvas.height / 3;
return true;
}
function drawImg() {
ctx.drawImage(starCanvas, x, y, scaleX, scaleY);
return true;
}
function Loop() {
window.setTimeout(Loop, 100);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(backgroundImg, 0,0);
angle += Math.PI * 0.05;
x = center.x + radius * Math.cos(angle);
y = center.y + radius * Math.sin(angle);
vBox.value = slider.value;
updateStarScale();
drawImg();
}
function getStarImages() {
//as they're all the same image, you don't need to make an array of them, simply make a loop below
var img = new Image();
img.addEventListener('load', drawBackgroundStar)
img.src = createStar();
return img;
}
function drawBackgroundStar() {
for (var i=0; i<500; i++) {
ctx.drawImage(image, getRandomArbitrary(0, canvas.width), getRandomArbitrary(0, canvas.height), getRandomArbitrary(5, 15), getRandomArbitrary(5, 15));
}
backgroundImg = new Image();
backgroundImg.addEventListener('load', Loop);
backgroundImg.src = canvas.toDataURL();
starCtx.drawImage(image, 0,0,50,50)
}
function updateStarScale() {
if (vBox.value > 0) {
scaleX += vBox.value / 10;
scaleY += vBox.value / 10;
changeImgColorToBlue();
} else if (vBox.value < 0) {
scaleX -= Math.abs(vBox.value / 10);
scaleY -= Math.abs(vBox.value / 10);
changeImgColorToRed();
}
if (scaleX > 600 || scaleY > 600) {
scaleX = 600;
scaleY = 600;
} else if (scaleX < 50 || scaleY < 50) {
scaleX = 50;
scaleY = 50;
}
}
function changeImgColorToBlue() {
imageData = starCtx.getImageData(0, 0, 50, 50);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
//is our data black?
if(data[i]>0||data[i+1]>0||data[i+2]>0){
data[i] = 0;// red
data[i + 1] = 0; // green
data[i + 2] = 255; // blue
}
}
starCtx.putImageData(imageData, 0, 0);
}
function changeImgColorToRed() {
imageData = starCtx.getImageData(0, 0, 50, 50);
data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
if(data[i]>0||data[i+1]>0||data[i+2]>0){
data[i] = 255;// red
data[i + 1] = 0; // green
data[i + 2] = 0; // blue
}
}
starCtx.putImageData(imageData, 0, 0);
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
start();
body {
text-align: center;
}
#container {
position: fixed;
color: red;
top: 0px;
left: 0px;
}
#textBox {
position: absolute;
top: 25px;
left: 5px;
}
#slider {
position: absolute;
top: 25px;
left: 200px;
}
<canvas id="canvas" width="1024" height="768"></canvas>
<div id="container">
<div id="textBox">
Velocity:
<input type="text" id="textbox" value="0">
</div>
<div id="slider">
Slider:
<form oninput="amount.value=rangeInput.value">
<input type="range" id="rangeInput" name="rangeInput" min="-100" max="100" step="3" value="">
<output name="amount" for="rangeInput">0</output>
</form>
</div>
</div>

Categories