Canvas isn't updating - javascript

I was planning on making a personal project with JavaScript until I encountered a problem. I have a canvas representing the HP
but it's not updating, I've tried Intervals but it didn't work either.
Code below:
<script>
var health=100;
var h = health;
var totalhealth=100;
var intNumber;
function hp(){
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var grd=ctx.createLinearGradient(0,0,170,0);
grd.addColorStop(0,"red");
grd.addColorStop(0.2,"#F4710E");
grd.addColorStop(1,"green");
ctx.fillStyle=grd;
ctx.fillRect(0,0,(h/100)*140,10);
document.getElementById("demo").innerHTML = h +"/"+totalhealth;
}
function punch(){
health-=1;
}
</script>
HTML code, it starts with onload="hp()"
<canvas id="myCanvas" width="140" height="10" style="border:2px solid #000000;"></canvas>
<p id="demo"></p>
<input type="button" value="Punch" onclick="punch()"/>

Call the hp function inside the punch function:
function punch() {
health -= 1;
hp();
}
You also need to clear the canvas before adding a smaller rectangle, so add a call to the canvas clearRect method in the hp function:
function hp() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0, 0, 170, 0);
grd.addColorStop(0, "red");
grd.addColorStop(0.2, "#F4710E");
grd.addColorStop(1, "green");
ctx.fillStyle = grd;
ctx.clearRect(0, 0, c.width, c.height); //<-- this
ctx.fillRect(0, 0, (health / 100) * 140, 10); //h changed to health
document.getElementById("demo").innerHTML = health + "/" + totalhealth; //h changed to health
}
hp(); //put this in the onload function, to initialize the health bar
DEMO

Related

Edit lineTo points (in canvas)

I want to move lineTo points.
How to do it?
I'm new to Canvas.
I'll give an example with Path.
This is my example:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
var line = ctx.lineTo(300, 100);
ctx.lineTo(70, 100);
ctx.lineTo(20, 20);
ctx.fillStyle = "red";
ctx.fill();
setTimeout(function() {
/*
I want something like this:
line.editpoints(300, 150);
*/
}, 3000);
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas>
Well, canvas as the name suggests, is a canvas (just like in paintings). You can draw on it, but you cannot move things on it as it is not "dynamic".
What you can do, though, is clear it and then draw on top at a different location.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
function clearContext(ctx) {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
function drawTriangle(offsetX = 0, offsetY = 0) {
ctx.beginPath();
ctx.moveTo(offsetX + 20, offsetY + 20);
var line = ctx.lineTo(offsetX + 300, offsetY + 100);
ctx.lineTo(offsetX + 70, offsetY + 100);
ctx.lineTo(offsetX + 20, offsetY + 20);
ctx.fillStyle = "red";
ctx.fill();
}
drawTriangle();
setTimeout(function() {
clearContext(ctx);
drawTriangle(50, 50);
}, 3000);
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #d3d3d3;"></canvas>

HTML5 Canvas clearRect isn't working

So I'm trying to have an 'X' appear on the screen and go across every second, but the previous 'X's don't go away when I draw the new ones, a whole path of 'X's stays behind and I want it to just be one that moves across in 60px increments. Obviously there must be something having to do with paths and such that I don't know about, here's my code:
//ctx is already defined as the canvas context and works fine
var bx = 0;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
setInterval(function(){
ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
ctx.moveTo(bx*60 ,0);
ctx.lineTo(bx*60+60,60);
ctx.moveTo(bx*60+60,0);
ctx.lineTo(bx*60 ,60);
ctx.stroke();
bx++;
},1000);
<canvas id="myCanvas" width="200" height="100"></canvas>
You forget to begin and close path. Your canvas go to clear but all your lines will be every iteration rerendered.
//ctx is already defined as the canvas context and works fine
var bx = 0;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
setInterval(function(){
ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
ctx.beginPath(); // begin
ctx.moveTo(bx*60 ,0);
ctx.lineTo(bx*60+60,60);
ctx.moveTo(bx*60+60,0);
ctx.lineTo(bx*60 ,60);
ctx.closePath(); // close
ctx.stroke();
bx++;
},1000);
Try this:
//ctx is already defined as the canvas context and works fine
var bx = 0;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
setInterval(function() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.beginPath();
ctx.moveTo(bx * 60, 0);
ctx.lineTo(bx * 60 + 60, 60);
ctx.moveTo(bx * 60 + 60, 0);
ctx.lineTo(bx * 60, 60);
ctx.closePath();
ctx.stroke();
bx++;
}, 1000);
<canvas id="myCanvas" width="200" height="100"></canvas>

Javascript Canvas one item flickering

I am trying to make to objects move towards each other in Canvas, when they meet and overlap one should then disappear and the other should fall down. Now I got the animation to do that, but one of the items is flickering.
<!DOCTYPE html>
<html>
<head>
<style>
canvas{border:#666 3px solid;}
</style>
</head>
<body onload="draw(530,15); draw1(1,15);">
<canvas id="canvas" width="600" height="400"></canvas>
<script>
function draw(x,y){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.save();
ctx.clearRect(x, y, 600, 400);
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect (x, y, 70, 50);
ctx.restore();
x -= 0.5;
if(x==300)
{
return;
};
var loopTimer = setTimeout('draw('+x+','+y+')',5);
};
function draw1(w,e){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.save();
ctx.clearRect(w-1,e-2,600,400);
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect (w, e, 70, 50);
ctx.restore();
w += 1;
if(w==265)
{
w -= 1;
e +=2;
};
var loopTimer = setTimeout('draw1('+w+','+e+')',10);
};
</script>
</body>
</html>
Been trying for two days, but can't seem to fix it properly. Thanks in advance.
You are rendering too many frames per second forcing the browser to present frames. Each time a draw function returns the browser presumes you want to present the frame to the page.
Animations need to be synced to the display refresh rate which for most devices is 60FPS. To do this you have one render loop that handles all the animation. You call this function via requestAnimationFrame (RAF) which ensures that the animation stays in sync with the display hardware and browser rendering.
<!DOCTYPE html>
<html>
<head>
<style>
canvas{border:#666 3px solid;}
</style>
</head>
<!-- dont need this <body onload="draw(530,15); draw1(1,15);">-->
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script>
var canvas,ctx,x,y,w,e;
var canvas,ctx,x,y,w,e;
function draw() {
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect(x, y, 70, 50);
};
function draw1(w, e) {
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect(w, e, 70, 50);
};
function update(time){ // high precision time passed by RAF when it calls this function
ctx.clearRect(0,0,canvas.width,canvas.height); // clear all of the canvas
if(w + 70 >= x){
e += 2;
}else{
x -= 0.75;
w += 1;
};
draw(x,y);
draw1(w,e);
requestAnimationFrame(update)
// at this point the function exits and the browser presents
// the canvas bitmap for display
}
function start(){ // set up
x = 530;
y = 15;
w = 1;
e = 15;
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
requestAnimationFrame(update)
}
window.addEventListener("load",start);
</script>
</body>
</html>
You're method of animation is very outdated (ie, the use of setTimeout). Instead you should be using requestAnimationFrame as demonstrated below. This will give smooth, flicker free animation.
<!DOCTYPE html>
<html>
<head>
<style>
canvas{border:#666 3px solid;}
</style>
</head>
<body onload="requestAnimationFrame(animate);">
<canvas id="canvas" width="600" height="400"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 530, y = 15;
function animate(){
requestID = requestAnimationFrame(animate);
ctx.clearRect(x, y, 600, 400);
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect (x, y, 70, 50);
x -= 0.5;
if(x==300)
{
cancelAnimationFrame(requestID)
};
}
</script>
</body>
</html>
the first 2 parameters of ctx.clearReact in both draw functions should be 0:
ctx.clearRect(0, 0, 600, 400);
This means you clear all canvas.

Adding Image within a canvas circle

I am learning drawing canvas and now I have task. I need to add an image within the inner circle. The image position needs to be inside the circle. Also I attached the image with this post. My code are:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0,0,200,100);
var cicleT = document.getElementById("myCanvas");
var dtx = cicleT.getContext("2d");
dtx.arc(95,50,40,0,2*Math.PI);
dtx.stroke();
dtx.fillStyle = "red";
dtx.fill();
dtx.fillStyle = "black"; // font color to write the text with
var font = "bold 13px serif";
dtx.font = font;
dtx.textBaseline = "bottom";
dtx.fillText("Bangladesh",50,50, 95 ,25);
</script>
</body>
</html>
You can use ctx.clip to cut out the region you want to draw, and the following operation will be refined on the region, remember to restore when you complete the works that needs to be refined.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 200, 100);
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
ctx.fillStyle = "red";
ctx.fill();
// For safety, I move the draw image and draw text to image.onload.
var image = document.createElement('img');
image.onload = function() {
var iw = image.width;
var ih = image.height;
var r = Math.sqrt(Math.pow(iw/2, 2) + Math.pow(ih/2, 2));
var ratio = 40 / r;
var tw = iw * ratio;
var th = ih * ratio;
// Use the same ctx is ok.
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
// Save the current state of context, which is not clipped yet.
ctx.save();
// Clip by the stroke.
ctx.clip();
// Draw image.
//
ctx.drawImage(image, 0, 0, iw, ih, 95 - tw/2, 50 - th/2, tw, th);
// Restore the context, otherwise the text will also be clipped.
ctx.restore();
ctx.fillStyle = "black"; // font color to write the text with
var font = "bold 13px serif";
ctx.font = font;
ctx.textBaseline = "bottom";
ctx.fillText("Bangladesh", 50, 50, 95, 25);
};
image.src = "https://i.stack.imgur.com/jy3YL.jpg";
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

Having trouble with canvas, I've followed online tutorials but nothing shows in browser window

I've been learning how to use html5 recently and one aspect that really interests me is the canvas's ability to create animations. I have followed some online tutorials to some success but recently I found "thecodeplayer" where there are some awesome tutorials (if your in to it, check it out). I've got to the point where I've gone through it various times but still with no luck. The canvas does not show in my browser window when I load it up in chrome. Ive even turned off extensions like adblocker as suggested from some answers on this site. Its probably something obvious but I cant find where I seem to have gone wrong. Anyone who can point me in the right direction, thanks
Heres the code.
<html>
<head>
<script type="text/javascript">
//Initializing the canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//Canvas dimensions
var W = 500; var H = 500;
//create an array of particles
var particles = [];
for(var i = 0; i < 50; i++)
{
//This will add 50 particles to the array with random positions
particles.push(new create_particle());
}
//function to create multiple particles
function create_particle()
{
//Random position on the canvas
this.x = Math.random()*W;
this.y = Math.random()*H;
//add random velocity to each particle
this.vx = Math.random()*20-10;
this.vy = Math.random()*20-10;
//Random colors
var r = Math.random()*255>>0;
var g = Math.random()*255>>0;
var b = Math.random()*255>>0;
this.color = "rgba("+r+", "+g+", "+b+", 0.5)";
//Random size
this.radius = Math.random()*20+20;
}
var x = 100; var y = 100;
//animate the particle
function draw()
{
//paint canvas black, remove particle trails
ctx.globalCompositeOperation = "source-over";
//reduce the opacity of the BG paint to give the final touch
ctx.fillStyle = "rgba(0, 0, 0, 0.3)";
ctx.fillRect(0, 0, W, H);
//blend the particle with the BG
ctx.globalCompositeOperation = "lighter";
//draw particles from the array now
for(var t = 0; t < particles.length; t++)
{
var p = particles[t];
ctx.beginPath();
//colors
var gradient = ctx.createRadialGradient(p.x, p.y, 0, p.x, p.y, p.radius);
gradient.addColorStop(0, "white");
gradient.addColorStop(0.4, "white");
gradient.addColorStop(0.4, p.color);
gradient.addColorStop(1, "black");
ctx.fillStyle = gradient;
ctx.arc(p.x, p.y, p.radius, Math.PI*2, false);
ctx.fill();
//velocity
p.x += p.vx;
p.y += p.vy;
//Stops balls moving out of canvas
if(p.x < -50) p.x = W+50;
if(p.y < -50) p.y = H+50;
if(p.x > W+50) p.x = -50;
if(p.y > H+50) p.y = -50;
}
}
setInterval(draw, 33);
</script>
</head>
<body>
<canvas id="canvas"width="500"height="500"></canvas>
</body>
</html>
Place the code in a function, and add a script tag below the body HTML, calling the canvas drawing function. The canvas element is not yet created when you want to use it for drawing on.
Result:
<html>
<head>
<script type="text/javascript">
function doCanvasStuff () {
//Initializing the canvas
var canvas = document.getElementById("canvas");
...
setInterval(draw, 33);
}
</script>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
<script>
doCanvasStuff();
</script>
</html>

Categories

Resources