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

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'

Related

How to remove black background from this JS coding?

I'm trying to make this particle text be on a transparent background to add onto a slideshow. Can someone assist? I cannot seem to find where it is stated within the code.
Here is the JS code. Sorry I can't seem to get it to fit properly within the code section of the post.
class Particles { constructor(x, y, texture, size) {
this.x = x;
this.y = y;
this.sprite = new PIXI.Sprite(new PIXI.Texture.from(texture));
this.sprite.texture.frame = new PIXI.Rectangle(x, y, size, size);
this.sprite.x = x;
this.sprite.y = y;
this.speedX = 0;
this.speedY = 0;
this.radius = 100;
this.gravity = 0.1;
this.maxGravity = 0.01 + Math.random() * 0.03;
this.friction = 0.9;
this.dirX = Math.random() - 0.5;
this.dirY = Math.random() - 0.5; }
update(mouse) {
const distanceX = mouse.x - this.sprite.x;
const distanceY = mouse.y - this.sprite.y;
const distanceSqrd = distanceX * distanceX + distanceY * distanceY;
if (distanceSqrd < this.radius * this.radius && distanceSqrd > 0) {
const distance = Math.sqrt(distanceSqrd);
let normalX = distanceX / distance;
let normalY = distanceY / distance;
this.speedX -= normalX;
this.speedY -= normalY;
this.gravity *= this.friction;
} else {
this.gravity += 0.1 * (this.maxGravity - this.gravity);
}
let oDistX = this.x - this.sprite.x;
let oDistY = this.y - this.sprite.y;
this.speedX += oDistX * this.gravity;
this.speedY += oDistY * this.gravity;
this.speedX *= this.friction;
this.speedY *= this.friction;
this.sprite.x += this.speedX;
this.sprite.y += this.speedY; } }
class ParticlesText { constructor({ text, size }) {
this.app = new PIXI.Application({ width: innerWidth, height: innerHeight });
document.querySelector("#content-canvas").append(this.app.view);
this.text = text;
this.size = size;
this.cols = 500;
this.rows = 200;
this.pSize = 2;
this.particles = [];
this.mouse = {x: 0, y: 0}
this.container = new PIXI.particles.ParticleContainer(50000);
this.app.stage.addChild(this.container);
this.onResize = this.onResize.bind(this); }
init() {
const that = this;
opentype.load(
"https://raw.githack.com/AlainBarrios/Fonts/master/LeagueSpartan-Bold.otf",
function(err, font) {
if (err) {
alert("Font could not be loaded: " + err);
} else {
const canvas = document.createElement("canvas");
// Now let's display it on a canvas with id "canvas"
const ctx = canvas.getContext("2d");
// Construct a Path object containing the letter shapes of the given text.
// The other parameters are x, y and fontSize.
// Note that y is the position of the baseline.
const path = font.getPath(that.text, 0, that.size, that.size);
const width = font.getAdvanceWidth(that.text, that.size);
that.cols = width;
that.rows = that.size;
canvas.width = width;
canvas.height = that.size;
path.fill = "rgba(255,255,255,1)";
// If you just want to draw the text you can also use font.draw(ctx, text, x, y, fontSize).
path.draw(ctx);
that.addObjects(canvas, ctx);
}
}
); }
isEmpty(x, y, ctx) {
const image = ctx.getImageData(x, y, this.pSize, this.pSize);
let emptyCounter = 0;
for (let i = 0; (length = image.data.length), i < length; i += 4) {
if (image.data[i + 3] !== 0) {
continue;
}
emptyCounter++;
}
return emptyCounter === this.pSize * this.pSize; }
addObjects(canvas, ctx) {
this.container.x = this.app.renderer.width / 2 - this.cols / 2;
this.container.y = this.app.renderer.height / 2 - this.rows / 2;
for (let i = 0; i < this.cols; i += 1) {
for (let j = 0; j < this.rows; j += 1) {
const x = i * this.pSize;
const y = j * this.pSize;
if (this.isEmpty(x, y, ctx)) continue;
const p = new Particles(x, y, canvas, this.pSize);
this.particles.push(p);
this.container.addChild(p.sprite);
}
}
this.container.interactive = true;
this.onResize();
window.addEventListener("resize", this.onResize);
this.container.on("mousemove", e => {
this.mouse = e.data.getLocalPosition(this.container);
});
this.animate(); }
onResize() {
const { innerWidth, innerHeight } = window;
const size = [innerWidth, innerHeight];
const ratio = size[0] / size[1];
if (innerWidth / innerHeight >= ratio) {
var w = innerHeight * ratio;
var h = innerHeight;
} else {
var w = innerWidth;
var h = innerWidth / ratio;
}
//this.app.renderer.view.style.width = w + "px";
//this.app.renderer.view.style.height = h + "px"; }
animate() {
this.app.ticker.add(() => {
stats.begin();
this.particles.forEach(p => {
p.update(this.mouse);
});
stats.end();
}); } }
const particles = new ParticlesText({ text: "KILL THE ROBOTS", size:
150 }); particles.init();

I need to make this canvas transparent but none of the solutions are working

I have tried all the jQuery tricks as well as the CSS tricks, but none of them work.. I don't really know anything about <canvas> but I've been trying to solve this for a day now.. can anybody help?
I am trying not mess up the code and just make the black background transparent so that I could use this canvas over a carousal..
// helper functions
const PI2 = Math.PI * 2
const random = (min, max) => Math.random() * (max - min + 1) + min | 0
const timestamp = _ => new Date().getTime()
// container
class Birthday {
constructor() {
this.resize()
// create a lovely place to store the firework
this.fireworks = []
this.counter = 0
}
resize() {
this.width = canvas.width = window.innerWidth
let center = this.width / 2 | 0
this.spawnA = center - center / 4 | 0
this.spawnB = center + center / 4 | 0
this.height = canvas.height = window.innerHeight
this.spawnC = this.height * .1
this.spawnD = this.height * .5
}
onClick(evt) {
let x = evt.clientX || evt.touches && evt.touches[0].pageX
let y = evt.clientY || evt.touches && evt.touches[0].pageY
let count = random(3, 5)
for (let i = 0; i < count; i++) this.fireworks.push(new Firework(
random(this.spawnA, this.spawnB),
this.height,
x,
y,
random(0, 260),
random(30, 110)))
this.counter = -1
}
update(delta) {
ctx.globalCompositeOperation = 'hard-light'
ctx.fillStyle = `rgba(20,20,20,${ 7 * delta })`
ctx.fillRect(0, 0, this.width, this.height)
ctx.globalCompositeOperation = 'lighter'
for (let firework of this.fireworks) firework.update(delta)
// if enough time passed... create new new firework
this.counter += delta * 3 // each second
if (this.counter >= 1) {
this.fireworks.push(new Firework(
random(this.spawnA, this.spawnB),
this.height,
random(0, this.width),
random(this.spawnC, this.spawnD),
random(0, 360),
random(30, 110)))
this.counter = 0
}
// remove the dead fireworks
if (this.fireworks.length > 1000) this.fireworks = this.fireworks.filter(firework => !firework.dead)
}
}
class Firework {
constructor(x, y, targetX, targetY, shade, offsprings) {
this.dead = false
this.offsprings = offsprings
this.x = x
this.y = y
this.targetX = targetX
this.targetY = targetY
this.shade = shade
this.history = []
}
update(delta) {
if (this.dead) return
let xDiff = this.targetX - this.x
let yDiff = this.targetY - this.y
if (Math.abs(xDiff) > 3 || Math.abs(yDiff) > 3) { // is still moving
this.x += xDiff * 2 * delta
this.y += yDiff * 2 * delta
this.history.push({
x: this.x,
y: this.y
})
if (this.history.length > 20) this.history.shift()
} else {
if (this.offsprings && !this.madeChilds) {
let babies = this.offsprings / 2
for (let i = 0; i < babies; i++) {
let targetX = this.x + this.offsprings * Math.cos(PI2 * i / babies) | 0
let targetY = this.y + this.offsprings * Math.sin(PI2 * i / babies) | 0
birthday.fireworks.push(new Firework(this.x, this.y, targetX, targetY, this.shade, 0))
}
}
this.madeChilds = true
this.history.shift()
}
if (this.history.length === 0) this.dead = true
else if (this.offsprings) {
for (let i = 0; this.history.length > i; i++) {
let point = this.history[i]
ctx.beginPath()
ctx.fillStyle = 'hsl(' + this.shade + ',100%,' + i + '%)'
ctx.arc(point.x, point.y, 1, 0, PI2, false)
ctx.fill()
}
} else {
ctx.beginPath()
ctx.fillStyle = 'hsl(' + this.shade + ',100%,50%)'
ctx.arc(this.x, this.y, 1, 0, PI2, false)
ctx.fill()
}
}
}
let canvas = document.getElementById('birthday')
let ctx = canvas.getContext('2d')
let then = timestamp()
let birthday = new Birthday
window.onresize = () => birthday.resize()
document.onclick = evt => birthday.onClick(evt)
document.ontouchstart = evt => birthday.onClick(evt)
;
(function loop() {
requestAnimationFrame(loop)
let now = timestamp()
let delta = now - then
then = now
birthday.update(delta / 1000)
})()
<canvas id="birthday"></canvas>
All you need to do is replace fillRect with clearRect in the update method of the Birthday class like this:
ctx.clearRect(0, 0, this.width, this.height)
You may need to make further adjustments to the color of the firework trail though, since it seems like it was supposed to match the background color.
If your canvas still isn't transparent, check your css to ensure that you're not setting the background color that way.
const PI2 = Math.PI * 2
const random = (min, max) => Math.random() * (max - min + 1) + min | 0
const timestamp = _ => new Date().getTime()
// container
class Birthday {
constructor() {
this.resize()
// create a lovely place to store the firework
this.fireworks = []
this.counter = 0
}
resize() {
this.width = canvas.width = window.innerWidth
let center = this.width / 2 | 0
this.spawnA = center - center / 4 | 0
this.spawnB = center + center / 4 | 0
this.height = canvas.height = window.innerHeight
this.spawnC = this.height * .1
this.spawnD = this.height * .5
}
onClick(evt) {
let x = evt.clientX || evt.touches && evt.touches[0].pageX
let y = evt.clientY || evt.touches && evt.touches[0].pageY
let count = random(3, 5)
for (let i = 0; i < count; i++) this.fireworks.push(new Firework(
random(this.spawnA, this.spawnB),
this.height,
x,
y,
random(0, 260),
random(30, 110)))
this.counter = -1
}
update(delta) {
ctx.globalCompositeOperation = 'hard-light'
ctx.fillStyle = `rgba(20,20,20,${ 7 * delta })`
ctx.clearRect(0, 0, this.width, this.height)
ctx.globalCompositeOperation = 'lighter'
for (let firework of this.fireworks) firework.update(delta)
// if enough time passed... create new new firework
this.counter += delta * 3 // each second
if (this.counter >= 1) {
this.fireworks.push(new Firework(
random(this.spawnA, this.spawnB),
this.height,
random(0, this.width),
random(this.spawnC, this.spawnD),
random(0, 360),
random(30, 110)))
this.counter = 0
}
// remove the dead fireworks
if (this.fireworks.length > 1000) this.fireworks = this.fireworks.filter(firework => !firework.dead)
}
}
class Firework {
constructor(x, y, targetX, targetY, shade, offsprings) {
this.dead = false
this.offsprings = offsprings
this.x = x
this.y = y
this.targetX = targetX
this.targetY = targetY
this.shade = shade
this.history = []
}
update(delta) {
if (this.dead) return
let xDiff = this.targetX - this.x
let yDiff = this.targetY - this.y
if (Math.abs(xDiff) > 3 || Math.abs(yDiff) > 3) { // is still moving
this.x += xDiff * 2 * delta
this.y += yDiff * 2 * delta
this.history.push({
x: this.x,
y: this.y
})
if (this.history.length > 20) this.history.shift()
} else {
if (this.offsprings && !this.madeChilds) {
let babies = this.offsprings / 2
for (let i = 0; i < babies; i++) {
let targetX = this.x + this.offsprings * Math.cos(PI2 * i / babies) | 0
let targetY = this.y + this.offsprings * Math.sin(PI2 * i / babies) | 0
birthday.fireworks.push(new Firework(this.x, this.y, targetX, targetY, this.shade, 0))
}
}
this.madeChilds = true
this.history.shift()
}
if (this.history.length === 0) this.dead = true
else if (this.offsprings) {
for (let i = 0; this.history.length > i; i++) {
let point = this.history[i]
ctx.beginPath()
ctx.fillStyle = 'hsl(' + this.shade + ',100%,' + i + '%)'
ctx.arc(point.x, point.y, 1, 0, PI2, false)
ctx.fill()
}
} else {
ctx.beginPath()
ctx.fillStyle = 'hsl(' + this.shade + ',100%,50%)'
ctx.arc(this.x, this.y, 1, 0, PI2, false)
ctx.fill()
}
}
}
let canvas = document.getElementById('birthday')
let ctx = canvas.getContext('2d')
let then = timestamp()
let birthday = new Birthday
window.onresize = () => birthday.resize()
document.onclick = evt => birthday.onClick(evt)
document.ontouchstart = evt => birthday.onClick(evt)
;
(function loop() {
requestAnimationFrame(loop)
let now = timestamp()
let delta = now - then
then = now
birthday.update(delta / 1000)
})()
div {
height : 100vh;
width : 100vw;
display : flex;
flex-direction : center;
align-items : center;
justify-content : center;
}
canvas {
position : absolute;
top : 0;
left : 0;
}
<div>Content Underneath</div>
<canvas id="birthday"></canvas>

jquery does not work with diango

I have a problem with this code. I cannot see the effect of this code in my html page. I use DJANGO framework with python.
I added jquery to my settings.py in my django project but should I do anything for it to be compatible with django?
var canvas = $('canvas')[0];
var context = canvas.getContext('2d');
var Dots = [];
var ID = 0;
var colors = ['#FF9900', '#424242', '#BCBCBC', '#3299BB','#B9D3B0','#81BDA4','#F88F79', '#F6AA93'];
var maximum = 100;
function Dot() {
this.active = true;
this.id = ID; ID++;
this.diameter = 2 + Math.random() * 7;
this.x = Math.round(Math.random() * canvas.width);
this.y = Math.round(Math.random() * canvas.height);
this.velocity = {
x: (Math.random() < 0.5 ? -1 : 1) * Math.random() * 0.4,
y: (Math.random() < 0.5 ? -1 : 1) * Math.random() * 0.4
};
this.alpha = 0.1;
this.maxAlpha = this.diameter < 5 ? 0.3 : 0.8;
this.hex = colors[Math.round(Math.random() * 7)];
this.color = HexToRGBA(this.hex, this.alpha);
}
Dot.prototype = {
Update: function() {
if(this.alpha <= this.maxAlpha) {
this.alpha += 0.005;
this.color = HexToRGBA(this.hex, this.alpha);
}
this.x += this.velocity.x;
this.y += this.velocity.y;
if(this.x > canvas.width + 5 || this.x < 0 - 5 || this.y > canvas.height + 5 || this.y < 0 - 5) {
this.active = false;
}
},
Draw: function() {
context.strokeStyle = this.color;
context.fillStyle = this.color;
context.save();
context.beginPath();
context.translate(this.x, this.y);
context.moveTo(0, -this.diameter);
for (var i = 0; i < 7; i++)
{
context.rotate(Math.PI / 7);
context.lineTo(0, -(this.diameter / 2));
context.rotate(Math.PI / 7);
context.lineTo(0, -this.diameter);
}
if(this.id % 2 == 0) {
context.stroke();
} else {
context.fill();
}
context.closePath();
context.restore();
}
}
function Update() {
GenerateDots();
Dots.forEach(function(Dot) {
Dot.Update();
});
Dots = Dots.filter(function(Dot) {
return Dot.active;
});
Render();
requestAnimationFrame(Update);
}
function Render() {
context.clearRect(0, 0, canvas.width, canvas.height);
Dots.forEach(function(Dot) {
Dot.Draw();
});
}
function GenerateDots() {
if(Dots.length < maximum) {
for(var i = Dots.length; i < maximum; i++) {
Dots.push(new Dot());
}
}
return false;
}
function HexToRGBA(hex, alpha) {
var red = parseInt((TrimHex(hex)).substring(0, 2), 16);
var green = parseInt((TrimHex(hex)).substring(2, 4), 16);
var blue = parseInt((TrimHex(hex)).substring(4, 6), 16);
return 'rgba(' + red + ', ' + green + ', ' + blue + ', ' + alpha + ')';
}
function TrimHex(hex) {
return (hex.charAt(0) == "#") ? hex.substring(1, 7) : hex;
}
function WindowSize(width, height) {
if(width != null) { canvas.width = width; } else { canvas.width = window.innerWidth; }
if(height != null) { canvas.height = height; } else { canvas.height = window.innerHeight; }
}
$(window).resize(function() {
Dots = [];
WindowSize();
});
WindowSize();
GenerateDots();
Update();
I found the problem...(silly one)
I got this error in my browser's console.ReferenceError: $ is not define
I just needed to load jquery library before my jquery code.

Clickable Canvas Button with Link

I have the following canvas. I want it so that when the user clicks the canvas, I will go to google.com, and I want to keep the button element. This is my code:
//set the variables
var a = document.getElementById('canvas'),
c = a.getContext('2d'),
a.style.width = '200px';
a.style.height = '50px';
area = w * h,
particleNum = 300,
ANIMATION;
var particles = [];
//create the particles
function Particle(i) {
this.id = i;
this.hue = rand(50, 0, 1);
this.active = false;
}
Particle.prototype.build = function() {
this.x = w / 2;
this.y = h / 2;
this.r = rand(7, 2, 1);
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = .01;
this.opacity = Math.random() + .5;
this.active = true;
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
};
Particle.prototype.draw = function() {
this.active = true;
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.hue -= 0.5;
this.r = Math.abs(this.r - .05);
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
// reset particle
if(this.r <= .05) {
this.active = false;
}
};
//functionality
function drawScene() {
c.fillStyle = "black";
c.fillRect(0,0,w,h);
for(var i = 0; i < particles.length; i++) {
if(particles[i].active === true) {
particles[i].draw();
} else {
particles[i].build();
}
}
ANIMATION = requestAnimationFrame(drawScene);
}
function initCanvas() {
var s = getComputedStyle(a);
if(particles.length) {
particles = [];
cancelAnimationFrame(ANIMATION);
ANIMATION;
console.log(ANIMATION);
}
w = a.width = window.innerWidth;
h = a.height = window.innerHeight;
for(var i = 0; i < particleNum; i++) {
particles.push(new Particle(i));
}
drawScene();
console.log(ANIMATION);
}
//init
(function() {
initCanvas();
addEventListener('resize', initCanvas, false);
})();
//helper functions
function rand(max, min, _int) {
var max = (max === 0 || max)?max:1,
min = min || 0,
gen = min + (max - min) * Math.random();
return (_int) ? Math.round(gen) : gen;
};
#canvas{
width: 200;
height: 50;
}
<div class="wrapper">
<a href="index.html">
<button align=center onclick="handleClick()">
<canvas width="200" height="50" id="canvas" align=center></canvas>
<span class="text">SUBMIT</span>
</button>
</a>
</div>
Although, I only see the button, and no the canvas. How can I fix this?
You got a lot of errors actually buddy (variable declaration is the biggest problem) but by following the errors will give you a way to fix it, I don't know if this is the fix you want.
//set the variables
var a = document.getElementById('canvas'),
c = a.getContext('2d');
a.style.width = '200px';
a.style.height = '50px';
var w, h;
var area = w * h,
particleNum = 300,
ANIMATION;
var particles = [];
//create the particles
function Particle(i) {
this.id = i;
this.hue = rand(50, 0, 1);
this.active = false;
}
Particle.prototype.build = function() {
this.x = w / 2;
this.y = h / 2;
this.r = rand(7, 2, 1);
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = 0.01;
this.opacity = Math.random() + .5;
this.active = true;
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
};
Particle.prototype.draw = function() {
this.active = true;
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.hue -= 0.5;
this.r = Math.abs(this.r - 0.05);
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
// reset particle
if (this.r <= 0.05) {
this.active = false;
}
};
//functionality
function drawScene() {
c.fillStyle = "black";
c.fillRect(0, 0, w, h);
for (var i = 0; i < particles.length; i++) {
if (particles[i].active === true) {
particles[i].draw();
} else {
particles[i].build();
}
}
ANIMATION = requestAnimationFrame(drawScene);
}
function initCanvas() {
var s = getComputedStyle(a);
if (particles.length) {
particles = [];
cancelAnimationFrame(ANIMATION);
ANIMATION;
console.log(ANIMATION);
}
w = a.width = window.innerWidth;
h = a.height = window.innerHeight;
for (var i = 0; i < particleNum; i++) {
particles.push(new Particle(i));
}
drawScene();
console.log(ANIMATION);
}
//init
(function() {
initCanvas();
addEventListener('resize', initCanvas, false);
})();
//helper functions
function rand(max, min, _int) {
var max = (max === 0 || max) ? max : 1,
min = min || 0,
gen = min + (max - min) * Math.random();
return (_int) ? Math.round(gen) : gen;
};
#canvas {
width: 200px;
height: 50px;
}
<div class="wrapper">
<a href="index.html">
<button align=center onclick="handleClick()">
<canvas width="200" height="50" id="canvas" align=center> </canvas>
<span class="text">SUBMIT</span>
</button>
</a>
</div>

Resizing a <canvas> Element

I have the following canvas. I'm trying to make it smaller using the width and height attributes, but it doesn't work. This is my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="canvas" width="200" height="50"></canvas>
<script>
//set the variables
var a = document.getElementById('canvas'),
c = a.getContext('2d'),
w = a.width = window.innerWidth,
h = a.height = window.innerHeight,
area = w * h,
particleNum = 300,
ANIMATION;
var particles = [];
//create the particles
function Particle(i) {
this.id = i;
this.hue = rand(50, 0, 1);
this.active = false;
}
Particle.prototype.build = function() {
this.x = w / 2;
this.y = h / 2;
this.r = rand(7, 2, 1);
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = .01;
this.opacity = Math.random() + .5;
this.active = true;
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
};
Particle.prototype.draw = function() {
this.active = true;
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.hue -= 0.5;
this.r = Math.abs(this.r - .05);
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
// reset particle
if(this.r <= .05) {
this.active = false;
}
};
//functionality
function drawScene() {
c.fillStyle = "black";
c.fillRect(0,0,w,h);
for(var i = 0; i < particles.length; i++) {
if(particles[i].active === true) {
particles[i].draw();
} else {
particles[i].build();
}
}
ANIMATION = requestAnimationFrame(drawScene);
}
function initCanvas() {
var s = getComputedStyle(a);
if(particles.length) {
particles = [];
cancelAnimationFrame(ANIMATION);
ANIMATION;
console.log(ANIMATION);
}
w = a.width = window.innerWidth;
h = a.height = window.innerHeight;
for(var i = 0; i < particleNum; i++) {
particles.push(new Particle(i));
}
drawScene();
console.log(ANIMATION);
}
//init
(function() {
initCanvas();
addEventListener('resize', initCanvas, false);
})();
//helper functions
function rand(max, min, _int) {
var max = (max === 0 || max)?max:1,
min = min || 0,
gen = min + (max - min) * Math.random();
return (_int) ? Math.round(gen) : gen;
};
</script>
</body>
</html>
Pay more attention here:
var a = document.getElementById('canvas'),
c = a.getContext('2d'),
w = a.width = window.innerWidth,
h = a.height = window.innerHeight,
area = w * h,
As you can see, w is the width of the window and h is the height of the window. Try to edit w and h variable with custom values and tell me if it worked ;)
EDIT:
Simply replace h and w with this in your script tag:
a.style.width = '500px'; //random value, insert custom here
a.style.height = '500px';

Categories

Resources