I am unable to use canvas as background - javascript

I want to use one canvas as background for my <section> i saw some post like this one Use <canvas> as a CSS background and try some things but nothing work and i cant figure whats wrong. Maybe it can be done right through js.
This is my js to create canvas
/**/ /* ---- CORE ---- */
/**/var canvas = document.createElement('canvas');
var firstblock = document.getElementById('ifb');
/**/var context = canvas.getContext('2d');
/**/var windowWidth = canvas.width = document.getElementById("ifb").offsetWidth +1;
/**/var windowHeight = canvas.height = document.getElementById("ifb").offsetHeight +1;
/**/canvas.id = 'canvas';
firstblock.appendChild(canvas)
/**/ /* ---- CORE END ---- */
/* ---- CREATING ZONE ---- */
/* ---- SETTINGS ---- */
var numberParticlesStart = 100;
var particleSpeed = 20.3;
var velocity = 0.9;
var circleWidth = 200;
/* ---- INIT ---- */
var particles = [];
var getRandomFloat = function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
};
/* ---- Particle ---- */
function Particle(x, y) {
this.x = x;
this.y = y;
this.vel = {
x: getRandomFloat(-20, 20) / 100,
y: getRandomFloat(-20, 20) / 100,
min: getRandomFloat(2, 10),
max: getRandomFloat(10, 100) / 10
};
this.color = 'rgba(255, 255, 255, 0.25)';
}
Particle.prototype.render = function () {
context.beginPath();
context.fillStyle = this.color;
context.arc(this.x, this.y, 1, 0, Math.PI * 2);
context.fill();
};
Particle.prototype.update = function () {
var forceDirection = {
x: getRandomFloat(-1, 1),
y: getRandomFloat(-1, 1)
};
if (Math.abs(this.vel.x + forceDirection.x) < this.vel.max) {
this.vel.x += forceDirection.x;
}
if (Math.abs(this.vel.y + forceDirection.y) < this.vel.max) {
this.vel.y += forceDirection.y;
}
this.x += this.vel.x * particleSpeed;
this.y += this.vel.y * particleSpeed;
if (Math.abs(this.vel.x) > this.vel.min) {
this.vel.x *= velocity;
}
if (Math.abs(this.vel.y) > this.vel.min) {
this.vel.y *= velocity;
}
this.testBorder();
};
Particle.prototype.testBorder = function () {
if (this.x > windowWidth) {
this.setPosition(this.x, 'x');
} else if (this.x < 0) {
this.setPosition(windowWidth, 'x');
}
if (this.y > windowHeight) {
this.setPosition(this.y, 'y');
} else if (this.y < 0) {
this.setPosition(windowHeight, 'y');
}
};
Particle.prototype.setPosition = function (pos, coor) {
if (coor === 'x') {
this.x = pos;
} else if (coor === 'y') {
this.y = pos;
}
};
/* ---- Functions ----*/
function loop() {
var i = void 0;
var length = particles.length;
for (i = 0; i < length; i++) {
particles[i].update();
particles[i].render();
}
requestAnimationFrame(loop);
}
/* ---- START ---- */
function init() {
var i = void 0;
for (i = 0; i < numberParticlesStart; i++) {
var angle = Math.random() * 360;
particles.push(new Particle(windowWidth * 0.5 + Math.cos(angle) * circleWidth, windowHeight * 0.5 - Math.sin(angle) * circleWidth));
}
}
init();
window.onresize = function () {
windowWidth = canvas.width = window.innerWidth;
windowHeight = canvas.height = window.innerHeight;
particles = [];
context.clearRect(0, 0, windowWidth, windowHeight);
init();
};
loop();
And this is my html
<section style="height:100%;">
<div class="ip_first_block" id="ifb">
</div>
</section>
One of my attemps:
<section style="height:100%;background: -moz-element(#canvas)">
<div class="ip_first_block" id="ifb">
</div>
</section>

If you want to use canvas as a background so you can use layering concept. you can adjust canvas layer behind main layer. You can help from this code -
// html
<section>
<canvas id="canvas" height="300" width="300"></canvas>
<div></div>
</section>
//css
section {
position: relative;
}
canvas {
border: 1px solid;
position: absolute;
}
div {
height: 300px;
width: 300px;
position: absolute;
border: 1px solid red;
}
//js
var dom = document.getElementById("canvas");
var ctx = dom.getContext("2d");
ctx.fillRect(100, 100, 100, 100);

Related

I have an issue in my canvas. I want to change the color of particles. currently they are in red color. How can I change...?

I have a issue in my canvas. i want to change the color of particles. currently they are in black color. How i can change..? here is my code please let me know if u have any solution. I have a issue in my canvas. i want to change the color of particles. currently they are in red color. How i can change..?
Here my source code:
`
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<style>
html, body {
height: 100%;
padding: 0;
margin: 0;
background: rgba(0, 0, 0, 0.879);
}
canvas {
position: absolute;
width: 100%;
height: 100%;
}
</style>
</HEAD>
<BODY>
<canvas id="pinkboard"></canvas>
<script>
/*
* Settings
*/
var settings = {
particles: {
length: 300, // maximum amount of particles
duration: 2, // particle duration in sec
velocity: 100, // particle velocity in pixels/sec
effect: -0.75, // play with this for a nice effect
size: 30, // particle size in pixels
},
};
/*
* RequestAnimationFrame polyfill by Erik Möller
*/
(function(){var b=0;var c=["ms","moz","webkit","o"];for(var a=0;a<c.length&&!window.requestAnimationFrame;++a){window.requestAnimationFrame=window[c[a]+"RequestAnimationFrame"];window.cancelAnimationFrame=window[c[a]+"CancelAnimationFrame"]||window[c[a]+"CancelRequestAnimationFrame"]}if(!window.requestAnimationFrame){window.requestAnimationFrame=function(h,e){var d=new Date().getTime();var f=Math.max(0,16-(d-b));var g=window.setTimeout(function(){h(d+f)},f);b=d+f;return g}}if(!window.cancelAnimationFrame){window.cancelAnimationFrame=function(d){clearTimeout(d)}}}());
/*
* Point class
*/
var Point = (function() {
function Point(x, y) {
this.x = (typeof x !== 'undefined') ? x : 0;
this.y = (typeof y !== 'undefined') ? y : 0;
}
Point.prototype.clone = function() {
return new Point(this.x, this.y);
};
Point.prototype.length = function(length) {
if (typeof length == 'undefined')
return Math.sqrt(this.x * this.x + this.y * this.y);
this.normalize();
this.x *= length;
this.y *= length;
return this;
};
Point.prototype.normalize = function() {
var length = this.length();
this.x /= length;
this.y /= length;
return this;
};
return Point;
})();
/*
* Particle class
*/
var Particle = (function() {
function Particle() {
this.position = new Point();
this.velocity = new Point();
this.acceleration = new Point();
this.age = 0;
}
Particle.prototype.initialize = function(x, y, dx, dy) {
this.position.x = x;
this.position.y = y;
this.velocity.x = dx;
this.velocity.y = dy;
this.acceleration.x = dx * settings.particles.effect;
this.acceleration.y = dy * settings.particles.effect;
this.age = 0;
};
Particle.prototype.update = function(deltaTime) {
this.position.x += this.velocity.x * deltaTime;
this.position.y += this.velocity.y * deltaTime;
this.velocity.x += this.acceleration.x * deltaTime;
this.velocity.y += this.acceleration.y * deltaTime;
this.age += deltaTime;
};
Particle.prototype.draw = function(context, image) {
function ease(t) {
return (--t) * t * t + 1;
}
var size = image.width * ease(this.age / settings.particles.duration);
context.globalAlpha = 1 - this.age / settings.particles.duration;
context.drawImage(image, this.position.x - size / 2, this.position.y - size / 2, size, size);
};
return Particle;
})();
/*
* ParticlePool class
*/
var ParticlePool = (function() {
var particles,
firstActive = 0,
firstFree = 0,
duration = settings.particles.duration;
function ParticlePool(length) {
// create and populate particle pool
particles = new Array(length);
for (var i = 0; i < particles.length; i++)
particles[i] = new Particle();
}
ParticlePool.prototype.add = function(x, y, dx, dy) {
particles[firstFree].initialize(x, y, dx, dy);
// handle circular queue
firstFree++;
if (firstFree == particles.length) firstFree = 0;
if (firstActive == firstFree ) firstActive++;
if (firstActive == particles.length) firstActive = 0;
};
ParticlePool.prototype.update = function(deltaTime) {
var i;
// update active particles
if (firstActive < firstFree) {
for (i = firstActive; i < firstFree; i++)
particles[i].update(deltaTime);
}
if (firstFree < firstActive) {
for (i = firstActive; i < particles.length; i++)
particles[i].update(deltaTime);
for (i = 0; i < firstFree; i++)
particles[i].update(deltaTime);
}
// remove inactive particles
while (particles[firstActive].age >= duration && firstActive != firstFree) {
firstActive++;
if (firstActive == particles.length) firstActive = 0;
}
};
ParticlePool.prototype.draw = function(context, image) {
// draw active particles
if (firstActive < firstFree) {
for (i = firstActive; i < firstFree; i++)
particles[i].draw(context, image);
}
if (firstFree < firstActive) {
for (i = firstActive; i < particles.length; i++)
particles[i].draw(context, image);
for (i = 0; i < firstFree; i++)
particles[i].draw(context, image);
}
};
return ParticlePool;
})();
/*
* Putting it all together
*/
(function(canvas) {
var context = canvas.getContext('2d'),
particles = new ParticlePool(settings.particles.length),
particleRate = settings.particles.length / settings.particles.duration, // particles/sec
time;
// get point on heart with -PI <= t <= PI
function pointOnHeart(t) {
return new Point(
160 * Math.pow(Math.sin(t), 3),
130 * Math.cos(t) - 50 * Math.cos(2 * t) - 20 * Math.cos(3 * t) - 10 * Math.cos(4 * t) + 25
);
}
// creating the particle image using a dummy canvas
var image = (function() {
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d');
canvas.width = settings.particles.size;
canvas.height = settings.particles.size;
// helper function to create the path
function to(t) {
var point = pointOnHeart(t);
point.x = settings.particles.size / 2 + point.x * settings.particles.size / 350;
point.y = settings.particles.size / 2 - point.y * settings.particles.size / 350;
return point;
}
// create the path
context.beginPath();
var t = -Math.PI;
var point = to(t);
context.moveTo(point.x, point.y);
while (t < Math.PI) {
t += 0.01; // baby steps!
point = to(t);
context.lineTo(point.x, point.y);
}
context.closePath();
// create the fill
context.fillStyle = '#ea80b0';
context.fill();
// create the image
var image = new Image();
image.src = canvas.toDataURL();
return image;
})();
// render that thing!
function render() {
// next animation frame
requestAnimationFrame(render);
// update time
var newTime = new Date().getTime() / 1000,
deltaTime = newTime - (time || newTime);
time = newTime;
// clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// create new particles
var amount = particleRate * deltaTime;
for (var i = 0; i < amount; i++) {
var pos = pointOnHeart(Math.PI - 2 * Math.PI * Math.random());
var dir = pos.clone().length(settings.particles.velocity);
particles.add(canvas.width / 2 + pos.x, canvas.height / 2 - pos.y, dir.x, -dir.y);
}
// update and draw particles
particles.update(deltaTime);
particles.draw(context, image);
}
// handle (re-)sizing of the canvas
function onResize() {
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
}
window.onresize = onResize;
// delay rendering bootstrap
setTimeout(function() {
onResize();
render();
}, 10);
})(document.getElementById('pinkboard'));
</script>
</BODY>
</HTML>
`
I ended up with a red heart effect, how do I change it to blue

Canvas particle animation mobile touch event with elements positioned on top

I have this canvas particle animation that follows the mouse event correctly but it does not follow a touch event on mobile. I realized that it's because I have this animation beneath the rest of the content which is positioned on top. When there is something on top of the canvas that it's hitting, it does not trigger the touch event. I'm hoping someone can help me figure out how to avoid this issue so that the animation will still follow the user underneath the page content.
JS
var PI2 = Math.PI * 2;
var HALF_PI = Math.PI / 2;
var isTouch = 'ontouchstart' in window;
var isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/);
function Canvas(options) {
options = _.clone(options || {});
this.options = _.defaults(options, this.options);
this.el = this.options.el;
this.ctx = this.el.getContext('2d');
this.dpr = window.devicePixelRatio || 1;
this.updateDimensions();
window.addEventListener('resize', this.updateDimensions.bind(this), false);
this.resetTarget();
if(isTouch){
// touch
this.el.addEventListener('touchstart', this.touchMove.bind(this), false);
this.el.addEventListener('touchmove', this.touchMove.bind(this), false);
// this.el.addEventListener('touchend', this.resetTarget.bind(this), false);
} else {
// Mouse
window.addEventListener('mousemove', this.mouseMove.bind(this), false);
window.addEventListener('mouseout', this.resetTarget.bind(this), false);
}
this.setupParticles();
this.loop();
}
Canvas.prototype.updateDimensions = function() {
this.width = this.el.width = _.result(this.options, 'width') * this.dpr;
this.height = this.el.height = _.result(this.options, 'height') * this.dpr;
this.el.style.width = _.result(this.options, 'width') + 'px';
this.el.style.height = _.result(this.options, 'height') + 'px';
}
// Update the orb target
Canvas.prototype.mouseMove = function(event) {
this.target = new Vector(event.clientX * this.dpr, event.clientY* this.dpr);
}
// Reset to center when we mouse out
Canvas.prototype.resetTarget = function() {
this.target = new Vector(this.width / 2, this.height /2);
}
// Touch Eent
Canvas.prototype.touchMove = function(event) {
if(event.touches.length === 1) { event.preventDefault(); }
this.target = new Vector(event.touches[0].pageX * this.dpr, event.touches[0].pageY * this.dpr);
}
// Defaults
Canvas.prototype.options = {
count: 11,
speed: 0.001,
width: 400,
height: 400,
size: 5,
radius: 1,
background: '240, 240, 240, 0.6',
maxDistance: 100
}
Canvas.prototype.setupParticles = function() {
this.particles = [];
var index = -1;
var between = PI2 / this.options.count;
while(++index < this.options.count) {
var x;
var y;
var angle;
var max = Math.max(this.width, this.height);
angle = (index + 1) * between;
x = Math.cos(angle) * max;
x += this.width / 2;
y = Math.sin(angle) * max;
y += this.height / 2;
var particle = new Particle({
x: x,
y: y,
radius: this.options.radius,
size: this.options.size,
angle: angle,
color: this.options.color
});
this.particles.push(particle);
}
}
Canvas.prototype.findClosest = function() {
var index = -1;
var pointsLength = this.particles.length;
while(++index < pointsLength) {
var closestIndex = -1;
this.particles[index].closest = [];
while(++closestIndex < pointsLength) {
var closest = this.particles[closestIndex];
var distance = this.particles[index].position.distanceTo(closest.position);
if(distance < this.options.maxDistance) {
var vector = new Vector(closest.position.x, closest.position.y);
vector.opacity = 1 - (distance / this.options.maxDistance);
vector.distance = distance;
this.particles[index].closest.push(vector);
}
}
}
}
Canvas.prototype.loop = function() {
// this.clear();
if(isTouch || isSafari) {
this.ghost();
} else {
this.ghostGradient();
}
if(this.options.maxDistance > 0) {
this.findClosest();
}
this.draw();
window.requestAnimationFrame(_.bind(this.loop, this));
}
Canvas.prototype.clear = function() {
this.ctx.clearRect(0, 0 , this.width, this.height);
}
Canvas.prototype.ghost = function() {
this.ctx.globalCompositeOperation = "source-over";
this.ctx.rect(0, 0 , this.width, this.height);
if(typeof this.options.background === 'string') {
this.ctx.fillStyle = "rgba(" + this.options.background + ")";
} else {
this.ctx.fillStyle = "rgba(" + this.options.background[0] + ")";
}
this.ctx.fill();
}
Canvas.prototype.ghostGradient = function() {
var gradient;
if(typeof this.options.background === 'string') {
this.ctx.fillStyle = 'rgba(' + this.options.background + ')';
} else {
var gradient = this.ctx.createLinearGradient(0, 0, 0, this.height);
var length = this.options.background.length;
for(var i = 0; i < length; i++){
gradient.addColorStop((i+1) / length, 'rgba(' + this.options.background[i] + ')');
}
this.ctx.fillStyle = gradient;
}
this.ctx.globalOpacity = 0.1;
this.ctx.globalCompositeOperation = "darken";
this.ctx.fillRect(0, 0 , this.width, this.height);
}
// Draw
Canvas.prototype.draw = function() {
var index = -1;
var length = this.particles.length;
while(++index < length) {
var point = this.particles[index];
var color = point.color || this.options.color;
point.update(this.target, index);
this.ctx.globalAlpha = 0.3;
this.ctx.globalCompositeOperation = "lighten";
this.ctx.fillStyle = 'rgb(' + color + ')';
this.ctx.beginPath();
this.ctx.arc(point.position.x, point.position.y, point.size, 0, PI2, false);
this.ctx.closePath();
this.ctx.fill();
if(this.options.maxDistance > 0) {
this.drawLines(point, color);
}
}
}
// Draw connecting lines
Canvas.prototype.drawLines = function (point, color) {
color = color || this.options.color;
var index = -1;
var length = point.closest.length;
this.ctx.globalAlpha = 0.2;
this.ctx.globalCompositeOperation = "screen";
this.ctx.lineCap = 'round';
while(++index < length) {
this.ctx.lineWidth = (point.size * 2) * point.closest[index].opacity;
this.ctx.strokeStyle = 'rgba(250,250,250, ' + point.closest[index].opacity + ')';
this.ctx.beginPath();
this.ctx.moveTo(point.position.x, point.position.y);
this.ctx.lineTo(point.closest[index].x, point.closest[index].y);
this.ctx.stroke();
}
}
function Particle(options) {
options = _.clone(options || {});
this.options = _.defaults(options, this.options);
this.position = this.shift = new Vector(this.options.x, this.options.y);
this.speed = this.options.speed || 0.01 + Math.random() * 0.04;
this.angle = this.options.angle || 0;
if(this.options.color) {
var color = this.options.color.split(',');
var colorIndex = -1;
while(++colorIndex < 3) {
color[colorIndex] = Math.round(parseInt(color[colorIndex], 10) + (Math.random()*100)-50);
// Clamp
color[colorIndex] = Math.min(color[colorIndex], 255);
color[colorIndex] = Math.max(color[colorIndex], 0);
}
this.color = color.join(', ');
}
// Size
this.options.size = this.options.size || 7;
this.size = 1 + Math.random() * this.options.size;
this.targetSize = this.options.targetSize || this.options.size;
this.orbit = this.options.radius * 0.5 + (this.options.radius * 0.5 * Math.random());
}
Particle.prototype.update = function(target, index) {
this.angle += this.speed;
this.shift.x += (target.x - this.shift.x) * this.speed;
this.shift.y += (target.y - this.shift.y) * this.speed;
this.position.x = this.shift.x + Math.cos(index + this.angle) * this.orbit;
this.position.y = this.shift.y + Math.sin(index + this.angle) * this.orbit;
if(!isSafari) {
this.size += (this.targetSize - this.size) * 0.03;
if(Math.round(this.size) === Math.round(this.targetSize)) {
this.targetSize = 1 + Math.random() * this.options.size;
}
}
}
function Vector(x, y) {
this.x = x || 0;
this.y = y || 0;
}
Vector.prototype.distanceTo = function(vector, abs) {
var distance = Math.sqrt(Math.pow(this.x - vector.x, 2) + Math.pow(this.y - vector.y, 2));
return abs || false ? Math.abs(distance) : distance;
};
new Canvas({
el: document.getElementById('canvas'),
count: 25,
speed: 0.3,
radius: 6,
width: function() { return window.innerWidth; },
height: function() { return window.innerHeight; },
size: 15,
color: '30, 180, 1',
maxDistance: 100,
background: ['250,250,250,1', '215,216,215,0.8']
})
CSS
html, body {
min-height: 100%;
height: 100%;
}
#canvas {
width: 100%;
height: 100%;
position: fixed;
z-index: 100;
}
.page-content {
position: relative;
z-index: 900;
display: flex;
flex-direction: column;
}
HTML
<body>
<div id="container">
<canvas id="canvas"></canvas>
<div class="page-content">
</div>
</div>
</body>

How to add css in text in jquery please give me refrence

How to add css in text in jquery I have try but no way found it please help me.
let particles = [];
let frequency = 20;
// Popolate particles
setInterval(
function () {
popolate();
}.bind(this),
frequency);
let c1 = createCanvas({ width: jQuery(window).width(), height: jQuery(window).height() });
let c2 = createCanvas({ width: jQuery(window).width(), height: jQuery(window).height() });
let c3 = createCanvas({ width: jQuery(window).width(), height: jQuery(window).height() });
let tela = c1.canvas;
let canvas = c1.context;
// jQuery("body").append(tela);
jQuery("#text").append(c3.canvas);
writeText(c2.canvas, c2.context, "Create\nPublish\nDeliver")
jQuery("#text").css("background-color", "grey");
class Particle {
constructor(canvas, options) {
let random = Math.random();
this.canvas = canvas;
this.x = options.x;
this.y = options.y;
this.s = 3 + Math.random();
this.a = 0;
this.w = jQuery(window).width();
this.h = jQuery(window).height();
this.radius = 0.5 + Math.random() * 20;
this.color = this.radius > 5 ? "#FF5E4C" : "#ED413C"; //this.randomColor()
}
randomColor() {
let colors = ["#FF5E4C", "#FFFFFF"];
return colors[this.randomIntFromInterval(0, colors.length - 1)];
}
randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
render() {
this.canvas.beginPath();
this.canvas.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
this.canvas.lineWidth = 2;
this.canvas.fillStyle = this.color;
this.canvas.fill();
this.canvas.closePath();
}
move() {
//this.swapColor()
this.x += Math.cos(this.a) * this.s;
this.y += Math.sin(this.a) * this.s;
this.a += Math.random() * 0.8 - 0.4;
if (this.x < 0 || this.x > this.w - this.radius) {
return false;
}
if (this.y < 0 || this.y > this.h - this.radius) {
return false;
}
this.render();
return true;
}}
function createCanvas(properties) {
let canvas = document.createElement('canvas');
canvas.width = properties.width;
canvas.height = properties.height;
let context = canvas.getContext('2d');
return {
canvas: canvas,
context: context };
}
function writeText(canvas, context, text) {
let size = 100;
context.font = size + "px Montserrat";
context.fillStyle = "#111111";
context.textAlign = "center";
let lineheight = 70;
let lines = text.split('\n');
for (let i = 0; i < lines.length; i++) {
context.fillText(lines[i], canvas.width / 2, canvas.height / 2 + lineheight * i - lineheight * (lines.length - 1) / 3);
}
}
function maskCanvas() {
c3.context.drawImage(c2.canvas, 0, 0, c2.canvas.width, c2.canvas.height);
c3.context.globalCompositeOperation = 'source-atop';
c3.context.drawImage(c1.canvas, 0, 0);
blur(c1.context, c1.canvas, 2);
}
function blur(ctx, canvas, amt) {
ctx.filter = `blur(jQuery{amt}px)`;
ctx.drawImage(canvas, 0, 0);
ctx.filter = 'none';
}
/*
* Function to clear layer canvas
* #num:number number of particles
*/
function popolate() {
particles.push(
new Particle(canvas, {
x: jQuery(window).width() / 2,
y: jQuery(window).height() / 2 }));
return particles.length;
}
function clear() {
canvas.globalAlpha = 0.03;
canvas.fillStyle = '#111111';
canvas.fillRect(0, 0, tela.width, tela.height);
canvas.globalAlpha = 1;
}
function update() {
clear();
particles = particles.filter(function (p) {
return p.move();
});
maskCanvas();`enter code here`
requestAnimationFrame(update.bind(this));
}
update();
// jQuery("body").append(tela);
jQuery("#text").append(c3.canvas);
writeText(c2.canvas, c2.context, "Create\nPublish\nDeliver").css("margin-left:20px");
jQuery("#text").css("background-color", "grey");
I have not found any way to add css in text please help me these
This could be a possible solution
let elementStyle = document.getElementById('text').style
elementStyle.backgroundColor = 'red'
elementStyle.marginLeft = '20px'

HTML h1 tag not displaying correctly above javascript+css animation

I have the following code (from a code pen fork), and wish to add a simple Html H1 tag above the animation on the page. I have tried the below, but for some reason the H1 tag just displays for a second (flashes) and then disappears off the screen.
I have tried placing it in several places and also used tags, but the same thing happens.
Can someone please suggest a fix and also explain why this is occuring?
html, javascript file: and CSS File (style.css)
class Canvas {
constructor(element, ctx, w, h) {
this.element = element
this.ctx = ctx
this.width = w
this.height = h
this.interactive = false
this.playing = true
this.point = {
value: 150,
speed: 0.25,
limit: 70,
floor: 10,
up: true,
animating: false
}
this.multiplier = {
value: 1,
speed: 0.005,
limit: 20,
floor: 1,
up: true,
animating: true
}
this.center = {
x: w / 2,
y: h / 2,
targetX: w / 2,
targetY: h / 2,
easing: 0.02
}
this.radius = {
val: h / 2.2,
targetVal: h / 2.2,
easing: 0.02
}
document.body.addEventListener('click', this.click.bind(this))
document.body.addEventListener('mousemove', this.move.bind(this))
document.body.addEventListener('keyup', this.keyup.bind(this))
this.hue = 160
}
click(e) {
this.interactive = !this.interactive
if (!this.interactive) {
this.center.targetX = this.width / 2
this.center.targetY = this.height / 2
this.radius.targetVal = this.height / 2.2
this.element.classList.remove('interactive')
} else {
this.element.classList.add('interactive')
}
}
move(e) {
if (!this.interactive) {
return
}
const h3 = this.height / 3
this.center.targetX = e.pageX
this.center.targetY = Math.max(e.pageY, h3)
this.radius.targetVal = h3 + (e.pageY * 0.8)
}
keyup(e) {
if (e.which != 32) {
return
}
this.playing = !this.playing
if (this.playing && this.drawLoop) {
this.drawLoop()
}
}
update() {
this.clear()
this.animate(this.point)
this.animate(this.multiplier)
this.ease(this.center)
this.ease(this.radius)
this.hue += 0.3
const h = (this.hue % 360)
this.ctx.fillStyle = 'hsl(' + h + ',70%,20%)'
this.ctx.strokeStyle = 'hsla(' + h + ',80%,60%,0.2)'
this.ctx.globalCompositeOperation = 'lighter'
}
clear() {
this.ctx.globalCompositeOperation = 'source-over'
this.ctx.fillStyle = 'rgba(0,0,0,0.1)'
this.ctx.rect(0, 0, this.width, this.height)
this.ctx.fill()
}
draw() {
let radius = this.radius.val
const w2 = this.center.x,
h2 = this.center.y
this.ctx.beginPath()
this.ctx.shadowBlur = 0
this.ctx.shadowColor = 'black'
const points = this.point.value
const multiplier = this.multiplier.value
for (let p = 0; p < points; p++) {
const t = (p / points) * Math.PI * 2
const t2 = ((p * multiplier) / points) * Math.PI * 2
const x = radius * Math.cos(t) + w2
const y = radius * Math.sin(t) + h2
const x2 = radius * Math.cos(t2) + w2
const y2 = radius * Math.sin(t2) + h2
this.ctx.moveTo(x, y)
this.ctx.lineTo(x2, y2)
}
this.ctx.arc(w2, h2, radius, 0, 2 * Math.PI)
this.ctx.stroke()
this.ctx.closePath()
}
animate(object) {
if (!object.animating) {
return
}
if (object.up) {
object.value += object.speed
} else {
object.value -= object.speed
}
if (object.value > object.limit) {
object.up = false
} else if (object.value < object.floor) {
object.up = true
}
}
ease(object) {
if (object.val) {
const dv = object.targetVal - object.val
object.val += dv * object.easing
return
}
const dx = object.targetX - object.x
const dy = object.targetY - object.y
object.x += dx * object.easing
object.y += dy * object.easing
}
random(from, to) {
return from + (Math.rand() * (to - from))
}
resize(w, h) {
this.width = w
this.height = h
this.center.targetX = w / 2
this.center.targetY = h / 2
this.radius.targetVal = h / 2.2
}
}
(_ => {
const canvasElement = document.getElementById('canvas'),
ctx = canvasElement.getContext('2d')
let w = canvasElement.width = window.innerWidth,
h = canvasElement.height = window.innerHeight,
density = 1
const canvas = new Canvas(canvasElement, ctx, w, h)
function setup() {
window.addEventListener('resize', resize)
density = window.devicePixelRatio != undefined ? window.devicePixelRatio : 1.0
canvasElement.width = w * density
canvasElement.height = h * density
canvas.width = w
canvas.height = h
canvas.drawLoop = draw
ctx.scale(density, density)
draw()
}
function draw() {
canvas.update()
canvas.draw()
if (canvas.playing) {
window.requestAnimationFrame(draw)
}
}
function resize() {
w = canvasElement.width = window.innerWidth
h = canvasElement.height = window.innerHeight
canvasElement.width = w * density
canvasElement.height = h * density
canvas.resize(w, h)
ctx.scale(density, density)
}
setup()
})()
body {
background: #000;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
}
canvas.interactive {
cursor: none;
}
<html>
<head>
<link rel="stylesheet" href="style.css">
<center>
<h1>
<font color="white">This is the H1 Tag</font>
</h1>
</center>
</head>
<body>
<br>
<br>
<br>
<br>
<canvas id="canvas"></canvas>
Update
Thanks to the answer below, I have changed the css to the following, and the tag does display, but the animation is not centered. How can the canvas be re-positioned so that other 'elements' or objects can be fit around it?
canvas {
width: 30%;
height: 30%;
position: absolute;
left: 0;
top: 0;
}
This is because your canvas style is set to take up the whole page. Your h1 is also inside the head of the document. So that needs moved into the body too.
canvas {
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
}
If you remove the canvas style, your h1 will sit above the canvas.
Edit:
Reading between the lines OP wants the image scaled down and centered. I've created a Fiddle to show how this can be achieved.
Fiddle
Add some z-index to your h1 and remove the obsolete tags:
class Canvas {
constructor(element, ctx, w, h) {
this.element = element
this.ctx = ctx
this.width = w
this.height = h
this.interactive = false
this.playing = true
this.point = {
value: 150,
speed: 0.25,
limit: 70,
floor: 10,
up: true,
animating: false
}
this.multiplier = {
value: 1,
speed: 0.005,
limit: 20,
floor: 1,
up: true,
animating: true
}
this.center = {
x: w / 2,
y: h / 2,
targetX: w / 2,
targetY: h / 2,
easing: 0.02
}
this.radius = {
val: h / 2.2,
targetVal: h / 2.2,
easing: 0.02
}
document.body.addEventListener('click', this.click.bind(this))
document.body.addEventListener('mousemove', this.move.bind(this))
document.body.addEventListener('keyup', this.keyup.bind(this))
this.hue = 160
}
click(e) {
this.interactive = !this.interactive
if (!this.interactive) {
this.center.targetX = this.width / 2
this.center.targetY = this.height / 2
this.radius.targetVal = this.height / 2.2
this.element.classList.remove('interactive')
} else {
this.element.classList.add('interactive')
}
}
move(e) {
if (!this.interactive) {
return
}
const h3 = this.height / 3
this.center.targetX = e.pageX
this.center.targetY = Math.max(e.pageY, h3)
this.radius.targetVal = h3 + (e.pageY * 0.8)
}
keyup(e) {
if (e.which != 32) {
return
}
this.playing = !this.playing
if (this.playing && this.drawLoop) {
this.drawLoop()
}
}
update() {
this.clear()
this.animate(this.point)
this.animate(this.multiplier)
this.ease(this.center)
this.ease(this.radius)
this.hue += 0.3
const h = (this.hue % 360)
this.ctx.fillStyle = 'hsl(' + h + ',70%,20%)'
this.ctx.strokeStyle = 'hsla(' + h + ',80%,60%,0.2)'
this.ctx.globalCompositeOperation = 'lighter'
}
clear() {
this.ctx.globalCompositeOperation = 'source-over'
this.ctx.fillStyle = 'rgba(0,0,0,0.1)'
this.ctx.rect(0, 0, this.width, this.height)
this.ctx.fill()
}
draw() {
let radius = this.radius.val
const w2 = this.center.x,
h2 = this.center.y
this.ctx.beginPath()
this.ctx.shadowBlur = 0
this.ctx.shadowColor = 'black'
const points = this.point.value
const multiplier = this.multiplier.value
for (let p = 0; p < points; p++) {
const t = (p / points) * Math.PI * 2
const t2 = ((p * multiplier) / points) * Math.PI * 2
const x = radius * Math.cos(t) + w2
const y = radius * Math.sin(t) + h2
const x2 = radius * Math.cos(t2) + w2
const y2 = radius * Math.sin(t2) + h2
this.ctx.moveTo(x, y)
this.ctx.lineTo(x2, y2)
}
this.ctx.arc(w2, h2, radius, 0, 2 * Math.PI)
this.ctx.stroke()
this.ctx.closePath()
}
animate(object) {
if (!object.animating) {
return
}
if (object.up) {
object.value += object.speed
} else {
object.value -= object.speed
}
if (object.value > object.limit) {
object.up = false
} else if (object.value < object.floor) {
object.up = true
}
}
ease(object) {
if (object.val) {
const dv = object.targetVal - object.val
object.val += dv * object.easing
return
}
const dx = object.targetX - object.x
const dy = object.targetY - object.y
object.x += dx * object.easing
object.y += dy * object.easing
}
random(from, to) {
return from + (Math.rand() * (to - from))
}
resize(w, h) {
this.width = w
this.height = h
this.center.targetX = w / 2
this.center.targetY = h / 2
this.radius.targetVal = h / 2.2
}
}
(_ => {
const canvasElement = document.getElementById('canvas'),
ctx = canvasElement.getContext('2d')
let w = canvasElement.width = window.innerWidth,
h = canvasElement.height = window.innerHeight,
density = 1
const canvas = new Canvas(canvasElement, ctx, w, h)
function setup() {
window.addEventListener('resize', resize)
density = window.devicePixelRatio != undefined ? window.devicePixelRatio : 1.0
canvasElement.width = w * density
canvasElement.height = h * density
canvas.width = w
canvas.height = h
canvas.drawLoop = draw
ctx.scale(density, density)
draw()
}
function draw() {
canvas.update()
canvas.draw()
if (canvas.playing) {
window.requestAnimationFrame(draw)
}
}
function resize() {
w = canvasElement.width = window.innerWidth
h = canvasElement.height = window.innerHeight
canvasElement.width = w * density
canvasElement.height = h * density
canvas.resize(w, h)
ctx.scale(density, density)
}
setup()
})()
body {
background: #000;
overflow: hidden;
}
h1 {
position:relative;
z-index:2;
color:#fff;
text-align:center;
}
canvas {
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
}
canvas.interactive {
cursor: none;
}
<canvas id="canvas"></canvas>
<h1>This is a title</h1>
This is because of your canvas styles. If you add a margin-top to your canvas the h1 will not be removed, try it like this:
canvas {
margin-top: 200px;
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
}
You'll see that now your h1 is not dissapearing anymore.
Edit
Reading between the lines OP appears to want it scaled down and centered, so I've created a fiddle with updated code.
Fiddle

Moving an Object according to mouse coordinates

How do I get the following script to work? I wanted to be able to move the ship to the mouse coordinates. The space itself should move and the ship should stay in the centerview.
Would be great if you can modify the script as everybody writes his functions different.
Finally if the button is clicked I want the ship to move to that destination
I tried it when it worked and the ship never moved and I don't know if it has to do with the prototype.update function or not.
Is prototype.update or .render the same as if I would write this.update or this.render?
<script>
function domanDown(evt)
{
switch (evt)
{
case 38: /* Up arrow was pressed or button pressed*/
offsetY+=100 ;
break;
case 40: /* Down arrow was pressed or button pressed*/
offsetY-=100;
break;
case 37: /* Left arrow was pressedor button pressed*/
offsetX+=100;
break;
case 39: /* Right arrow was pressed or button pressed*/
offsetX-=100;
break;
}
}
window.requestAnimationFrame = function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(f) {
window.setTimeout(f,1e3/60);
}
}();
var Obj = function (x,y,sp,size){
this.size = size;
this.x = x;
this.y = y;
this.color = sp;
this.selected = 0;
}
var Planet_Class = function (x,y,sp){
this.type = 'Planet_Class';
this.depot = 11;
this.xtype = new Obj(x,y,sp,10);
w.objects.push(this);
Planet_Class.prototype.update =function () {
}
Planet_Class.prototype.render =function () {
ctx.save();
ctx.beginPath();
ctx.fillStyle = this.xtype.color;
ctx.fillRect(this.xtype.x, this.xtype.y,this.xtype.size,this.xtype.size);
ctx.fill();
ctx.restore();
}
}
var Usership = function(x,y,sp){
this.depot = 10;
this.type = 'Usership';
this.xtype = new Obj(x,y,sp,10);
w.objects.push(this);
Usership.prototype.update =function (x,y) {
this.xtype.x = x || 20;
this.xtype.y = y || 20;
}
Usership.prototype.render =function () {
ctx.save();
ctx.beginPath();
ctx.fillStyle = this.xtype.color;
ctx.fillRect(this.xtype.x, this.xtype.y,this.xtype.size,this.xtype.size);
ctx.fill();
ctx.restore();
}
}
var World = function(){
this.objects = new Array();
this.count = function(type,sp){
var cnt = 0;
for(var k = 0;k<this.objects.length;k++)
cnt++;
return cnt;
}
}
renderWorld = function(){
requestAnimationFrame(renderWorld);
var spliceArray = Array();
ctx.beginPath();
objcnt = w.objects.length;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "white";
ctx.fill();
i = 0;
while(i < objcnt){
w.objects[i].update();
w.objects[i].render();
if(w.objects[i].depot < 1)
spliceArray.push(i);
i++;
}
for(var k = 0;k<spliceArray.length;k++)
{
w.objects.splice(spliceArray[k],1); }
}
function r1(max,min){
return (Math.floor(Math.random() * (max - min)) + 1);
}
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d"),
width = 1024,
height = 768;
offsetX = (canvas.width/2)-300; /Startpoint x for the Ship
offsetY = (canvas.height/2)-300; /Startpoint y for the Ship
generateshipx = -offsetX + (canvas.width/2);
generateshipy = -offsetY + (canvas.height/2);
mX = generateshipx;
mY = generateshipy;
w = new World();
new Usership(generateshipx,generateshipy,'green');
for(i=1;i<4;i++){
new Planet_Class(r1(600,2),r1(600,2),'red');
}
canvas.addEventListener("click", function (e) {
mX = e.pageX- canvas.offsetLeft -offsetX) ;
mY = e.pageY - canvas.offsetTop -offsetY) ;
});
renderWorld();
</script>
<html>
<head>
</head>
<body style="background-color:black;">
<canvas style="z-index:1" width="1024" height="768" id="canvas"></canvas>
<input type="button" style="z-index:2; position:absolute; top:300; left:10" value="uo" onCLick="domanDown(38)()">
<input type="button" style="z-index:2; position:absolute; top:340; left:10" value="down" onCLick="domanDown(40)">
<input type="button" style="z-index:2; position:absolute; top:380; left:10" value="left" onCLick="domanDown(37)">
<input type="button" style="z-index:2; position:absolute; top:420; left:10" value="right" onCLick="domanDown(39)">
<input type="button" style="z-index:2; position:absolute; top:460; left:10" value="move" onCLick="moveObj()">
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
cursor: crosshair;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var bounds = null;
var isRotating = false;
var isMoving = false;
var pan = {
x: 0.0,
y: 0.0
};
var target = {
x: 0.0,
y: 0.0,
dist: 0.0
};
var ship = {
x: (canvasWidth * 0.5)|0,
y: (canvasHeight * 0.5)|0,
width: 10.0,
height: 10.0,
rotation: 0.0,
deltaRotation: 0.0
};
var stars = [];
stars.length = 100;
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
bounds = canvas.getBoundingClientRect();
for (var i = 0; i < stars.length; ++i) {
stars[i] = {
x: (Math.random() * 4 * canvasWidth - 2 * canvasWidth)|0,
y: (Math.random() * 4 * canvasHeight - 2 * canvasHeight)|0
};
}
loop();
}
window.onmousedown = function(e) {
isRotating = true;
isMoving = false;
target.x = pan.x + e.clientX - bounds.left;
target.y = pan.y + e.clientY - bounds.top;
}
function loop() {
// Tick
// Rotate to face target
if (isRotating) {
// Vector creation
var tX = ship.x - target.x;
var tY = ship.y - target.y;
var tL = Math.sqrt(tX**2 + tY**2);
var fX = Math.sin(ship.rotation);
var fY = -Math.cos(ship.rotation);
var sX = Math.sin(ship.rotation + Math.PI * 0.5);
var sY = -Math.cos(ship.rotation + Math.PI * 0.5);
// Normalization
tX = tX / tL;
tY = tY / tL;
// Left or right?
var a = 1.0 - Math.abs(tX * fX + tY * fY);
ship.rotation += 0.075 * (sX * tX + sY * tY < 0.0 ? 1.0 : -1.0);
if (a < 0.01) {
target.dist = tL;
isRotating = false;
isMoving = true;
}
}
// Accelerate to target
if (isMoving) {
ship.x += Math.sin(ship.rotation) * 1.0;
ship.y -= Math.cos(ship.rotation) * 1.0;
if (--target.dist < 0.0) {
isMoving = false;
}
}
// Render
// Update pan coordinates
pan.x = ship.x - canvasWidth * 0.5;
pan.y = ship.y - canvasHeight * 0.5;
// Draw background
ctx.fillStyle = "#222222";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
ctx.fillStyle = "white";
for (var i = 0; i < stars.length; ++i) {
ctx.fillRect(
stars[i].x - pan.x,
stars[i].y - pan.y,
2,
2
);
}
// Draw ship
ctx.strokeStyle = "white";
ctx.fillStyle = "darkred";
ctx.translate(canvasWidth * 0.5,canvasHeight * 0.5);
ctx.rotate(ship.rotation);
ctx.beginPath();
ctx.moveTo(-ship.width * 0.5,ship.height * 0.5);
ctx.lineTo(ship.width * 0.5,ship.height * 0.5);
ctx.lineTo(0.0,-ship.height * 0.5);
ctx.lineTo(-ship.width * 0.5,ship.height * 0.5);
ctx.fill();
ctx.stroke();
ctx.rotate(-ship.rotation);
ctx.translate(-canvasWidth * 0.5,-canvasHeight * 0.5);
requestAnimationFrame(loop);
}
</script>
</body>
</html>

Categories

Resources