HTML5 canvas animation not showing background image - javascript

I'm trying to do a simple animation where a bubble rises in a beer bottle and struggling with the background image. The beer image is not showing up. I only see the bubble rising.
My code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Bieranimation</title>
</head>
<body>
<div id="container">
<img class='img' src="https://i.imgur.com/VW3zcXq.jpg" alt="" />
<canvas id="bier" width="400" height="520" style="border:solid 1px">
</canvas>
</div>
<script type="text/javascript">
var c=document.getElementById("bier");
var ctx=c.getContext("2d");
var width = c.width; // Canvas Grösse
var heigth = c.height;
var x, y; // aktuelle x- und y-Koordinaten
var x0 = 50; // Start-Koordinaten
var y0 = 400;
var v0x = 0.05; // Geschwindigkeit in Pixel/Millisekunde
var v0y = 0.00005;
var dt = 20; // Zeitintervall in Millisekunden
var r = 40; // Radius
var zeit; // Aktuelle Laufzeit
var i = 0;
fZeichnen(ctx);
var aktiv = setInterval(function() {fZeichnen(ctx); }, dt);
function fZeichnen(context) {
// Für das Fade Out: Definition eines Alpha-Wertes
// für das Übermalen des vorhergehenden Bildzustandes
// Überdeckung 10%
// Vorhergehender Bildzustand wird mit der Füllfarbe und dem
// soeben definierten Alpha-Wert übermalt
context.fillRect(0,0,width,heigth);
// Die Ball-Zeichnung soll alles darunter liegende vollständig überdecken
// Überdeckung 100%
context.fillStyle="#FFFFFF"; // Grün
context.beginPath();
context.arc(x, y, r, 0, Math.PI*2, true);
context.closePath();
context.stroke();
// Kreis zeichnen und füllen
x = x0 + v0x; // Neue Koordinaten
y = y0 + v0y - zeit;
i += 0.1;
zeit = i * dt; // Gesamtlaufzeit
if (zeit >= 5000) {
clearInterval(aktiv)
}
}
</script>
</body>
</html>
I tried to do something with the z-index but it doesn't seem to work:
body{text-align: center;}
.img{position:absolute;z-index:-1;}
#container{
display:inline-block;
width: 400px;
height:520px;
margin: 0 auto;
position:relative;
}
#gameCanvas{
position:relative;
z-index:20;
}
I'd appreciate any kind of help.

(I'm not sure why I habitually try to answer questions in comments. Correcting that now.)
Canvases are transparent by default, but currently you're erasing your canvas each loop by filling it with white:
context.fillRect(0,0,width,heigth);
If you instead erase it (technically, fill it with a transparent color), you'll be able to see the elements stacked behind the canvas:
context.clearRect(0,0,width,heigth);

Related

How to paint a closed area which consists of separate lines on сanvas js?

I use canvas and draw a closed area and want the area to fill by some color. Here is how I do it. I draw closed area with lines
I draw line (1)
Next line (2) starts from end of the previous one
Last line (3) starts from end of line (2) and ends at the start of line (1)
So as result I have closed area and want to fill by some color
Here is the chunk of code I used:
context.fillStyle = '#8ED6FF';
context.fill();
But it not works. Неre is the code I use to accomplish the task.
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="978" height="900"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// begin custom shape
context.beginPath();
// line (1)
context.moveTo(10, 10);
context.lineTo(190, 190);
// line (2)
context.moveTo(190, 190);
context.lineTo(200, 280);
// line (3)
context.moveTo(200, 280);
context.lineTo(10, 10);
// here I try fill the area by color
context.fillStyle = '#8ED6FF';
context.fill();
context.stroke();
</script>
</body>
</html>
I found the solution.
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="978" height="900"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// begin custom shape
context.beginPath();
context.moveTo(70, 70);
context.lineTo(290, 290);
context.lineTo(300, 380);
context.closePath()
context.fillStyle = '#8ED6FF';
context.fill();
context.stroke();
</script>
</body>
</html>

How to stop a requestAnimationFrame on canvas in JavaScript [duplicate]

This question already has answers here:
How to stop a requestAnimationFrame recursion/loop?
(6 answers)
Closed 1 year ago.
little question. After googling how to do this for 8 hours a day, nothing. Please let me know how to stop a requestAnimationFrame: simply, just temporarily pause the animation:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width" />
<head>
<title>Parking Master LVL. 1</title>
</head>
<body>
<h3 id="header-style">Parking Master</h3>
<p class="paraGraph1">How to play:</p>
<ol id="directions">
<p>1. drive into the Green Outlined Square</p>
<p>2. do not crash through the process or the game ends!</p>
<p>3. press "<span><button style="position: relative;
top: -3px;
color: #11fc05;
border: 2px double #11fc05; width: 1.2em; height: 1.2em;"><span style="position: absolute; left: 4px;top: 0px; font-size: 0.6em;">Park</span></button></span>" when you parked in the correct spot.</p>
</ol>
</body>
<link rel="stylesheet" href="style.css">
<!--Game-->
<canvas id="myCanvas" width="600" height="400"
style="border:2px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<button style="position:absolute;left:550px;top:600px;" class="buttonDrive" onmousedown="mouseDown()" onmouseup="mouseUp()">Drive</button>
<button class="buttonPark" onclick="parkDetector()" style="position: absolute;left: 550px; top: 540px;"><strong>Park</strong></button>
<div id="Car-Body">
<script>
var canvas = document.getElementById('myCanvas'),
ctx = canvas.getContext('2d'),
x = 0,
last = performance.now();
function draw(timestamp) {
requestAnimationFrame(draw);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.rect(x, 20, 20, 20);
ctx.fillStyle = "#000000";
ctx.fill();
x += (timestamp - last) / 10;
last = timestamp;
}
</script>
</div>
<script>
var continueAnimating=true;
var carBody = document.getElementById("Car-Body");
// detect if car is parked
function parkDetector() {
if (carBody > 0) {
// If the car Parked in the correct spot
carIsParked();
}
}
// If the car is not parked in the correct spot
if (carBody < 176) {
function carIsNotParked() {
alert("Hmm... it doesn't seem like you parked!");
}
}
function carIsParked() {
alert("You Parked!");
document.body.innerHTML+=p;
document.body.innerHTML+='<button onclick="nextLevel()">Next Level</button>';
}
// Direct the car
var p = '<div></div>';
// Redirect to Next Level
function nextLevel() {
document.getElementsByClassName().innerHTML = 'Next Level';
}
function mouseUp() {
console.log('wow'); // if the "Drive" button is let go of, cancel the animation
}
function mouseDown() {
requestAnimationFrame(draw); // if "Drive" is pressed, draw the animation
}
</script>
Basically when the mouseDown Is functioned, it should trigger the requestAnimationFrame, which it does, but when mouseUp Event is triggered, it should stop the animation. I am new to javascript, and never did jQuery, please help.
You can use cancelAnimationFrame() to stop the animation. You can assign requestAnimationFrame() to a variable and then to stop the animation call that variable in the cancel function. You also don't need to call requestAnimationFrame() in the mouseDown function since just calling draw() will trigger it to be activated.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width" />
<head>
<title>Parking Master LVL. 1</title>
</head>
<body>
<h3 id="header-style">Parking Master</h3>
<p class="paraGraph1">How to play:</p>
<ol id="directions">
<p>1. drive into the Green Outlined Square</p>
<p>2. do not crash through the process or the game ends!</p>
<p>3. press "<span><button style="position: relative;
top: -3px;
color: #11fc05;
border: 2px double #11fc05; width: 1.2em; height: 1.2em;"><span style="position: absolute; left: 4px;top: 0px; font-size: 0.6em;">Park</span></button></span>" when you parked in the correct spot.</p>
</ol>
</body>
<link rel="stylesheet" href="style.css">
<!--Game-->
<canvas id="myCanvas" width="600" height="400" style="border:2px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<button style="position:absolute;left:550px;top:600px;" class="buttonDrive" onmousedown="mouseDown()" onmouseup="mouseUp()">Drive</button>
<button class="buttonPark" onclick="parkDetector()" style="position: absolute;left: 550px; top: 540px;"><strong>Park</strong></button>
<div id="Car-Body">
<script>
var canvas = document.getElementById('myCanvas'),
ctx = canvas.getContext('2d'),
x = 0,
last = performance.now(),
animate;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.rect(x, 20, 20, 20);
ctx.fillStyle = "#000000";
ctx.fill();
x += 0.5;
animate = requestAnimationFrame(draw);
}
</script>
</div>
<script>
var continueAnimating = true;
var carBody = document.getElementById("Car-Body");
// detect if car is parked
function parkDetector() {
if (carBody > 0) {
// If the car Parked in the correct spot
carIsParked();
}
}
// If the car is not parked in the correct spot
if (carBody < 176) {
function carIsNotParked() {
alert("Hmm... it doesn't seem like you parked!");
}
}
function carIsParked() {
alert("You Parked!");
document.body.innerHTML += p;
document.body.innerHTML += '<button onclick="nextLevel()">Next Level</button>';
}
// Direct the car
var p = '<div></div>';
// Redirect to Next Level
function nextLevel() {
document.getElementsByClassName().innerHTML = 'Next Level';
}
function mouseUp() {
console.log('wow');
cancelAnimationFrame(animate) // if the "Drive" button is let go of, cancel the animation
}
function mouseDown() {
draw();
// if "Drive" is pressed, draw the animation
}
</script>
You can change those functions like that :
var shouldDraw=false //Defines a new variable that will allow to draw or not
function draw(timestamp) {
if(!shouldDraw) return //Test if you should draw or not, if it is equal to true, the draw function continues as it should, otherwise it stops and isn't called again
requestAnimationFrame(draw);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
//The rest of your function...
}
function mouseUp() {
console.log('wow'); // if the "Drive" button is let go of, cancel the animation
shouldDraw=false //Says that you don't draw anymore
}
function mouseDown() {
shouldDraw=true //Says that you can draw now
requestAnimationFrame(draw); // if "Drive" is pressed, draw the animation
}

Draw More Arc Canvas

Hello People I'd Like to Know How to Draw More Arc Inside My Canvas, What I Need to Draw This circles:
So I Write This Responsive Code to Make my Canvas is Responsive:
var myCanvas = document.getElementById('myCanvas');
var ctx = myCanvas.getContext('2d');
var centerX = myCanvas.width / 2;
var centerY = myCanvas.height / 2;
var borderWidth = 20;
var borderColor = '#2DC36A';
var radius = (myCanvas.width / 2) - (borderWidth / 2);
// days arc canvas background
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.lineWidth = borderWidth;
ctx.strokeStyle = borderColor;
ctx.stroke();
ctx.closePath();
// Make Canvas Responsive
function makeResponsive() {
var containerWidth = $('.progress-nested').width();
$('.progress-nested').height(containerWidth);
var canvasElements = ['#myCanvas'];
$('#myCanvas').width(containerWidth).height(containerWidth);
}
makeResponsive(); // Make Canvas Responsive in Document ready
$(window).resize(function () {
makeResponsive(); // Make Canvas Responsive in Window Resize
});
#progress {
width: 100%;
padding: 5px;
}
.progress-nested{
position:relative;
border-radius:50%;
}
canvas {
display:block;
position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div id="progress">
<div class="container">
<div class="row">
<div class="col-xs-3 col-md-2 col-md-offset-2">
<div class="progress-nested">
<canvas id="myCanvas" width="250" height="250"></canvas>
</div>
</div>
</div>
</div>
</div>
Note: Please Run Code Snippet In Full Page

Javascript make an image bounce around screen

I have made code for a bouncing ball (using the arc() method on a canvas). I am wondering how to make an image bounce around the screen. Here is my previous code (note that the launchBall() function is going to be the function that runs the bouncing image):
<!DOCTYPE HTML>
<html>
<body onload="startBall()" oncontextmenu="return false;" style="cursor: none; overflow: hidden;">
<center>
<div id="div" style="width: 1600px; height: 700px; border: 2px solid #000000; background-color: grey;">
<br>
<img draggable="false"id="image" style="position: absolute;" width="50" height="50"src="http://www.clker.com/cliparts/b/a/b/0/1207156679935151925noxin_crosshairs.svg.hi.png"/>
</div>
<center>
<p>Score: <a>0</a></p>
</center>
<script>
var dx = 3;
var dy = 3;
var x = 100;
var y = 100;
var radius = 20;
var interval;
function startBall(){
interval = setInterval(launchBall, 20);
}
function launchBall(){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, 1275, 695);
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
document.getElementById
if(x<20 || x>1255) dx=-dx;
if(y<20 || y>675) dy=-dy;
x = x + dx;
y = y + dy;
}
document.getElementById("div").onmousemove = function(e) {
document.getElementById("image").style.top = e.pageY -25 + "px";
document.getElementById("image").style.left = e.pageX -25 +"px";
}
</script>
</body>
</html>

Jquery image hover, click and grayscale effect with tab and caption

i want my image get black white (grayscale) after i hover they will change to the color. it is already sucses, but i want if i click image they will change color, and show content in the div i already add .click .dblclick and .toogke function but always change image to the black and white here are the code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tabbed Navigation</title>
<style type="text/css">
.item {
width: auto;
margin: 0 0 0 0;
float: left;
}
.item.first {
clear: left;
margin-left: 0;
}
.item img {
opacity:0;
}
.wrapper{
float:left; /* important */
position:relative; /* important(so we can absolutely position the description div */
margin-right: 20px
}
.description{
position:absolute; /* absolute position (so we can position it where we want)*/
bottom:50px; /* position will be on bottom */
width:100%;
/* styling bellow */
background-color:black;
font-family: 'tahoma';
font-size:15px;
color:white;
opacity:0.6; /* transparency */
filter:alpha(opacity=60); /* IE transparency */
z-index: 9999;
}
p.description_content{
padding:5px;
margin:0px;
}
.item img a:active {
background-image: url(images/icondock.jpg);
}
</style>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
// $(".item img").css({"display":"none");
// On window load. This waits until images have loaded which is essential
$(window).load(function(){
// Fade in images so there isn't a color "pop" document load and then on window load
$(".item img").animate({opacity:1},500);
// clone image
$('.item img').each(function(){
var el = $(this);
el.css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"998","opacity":"0"}).insertBefore(el).queue(function(){
var el = $(this);
el.parent().css({"width":this.width,"height":this.height});
el.dequeue();
});
this.src = grayscale(this.src);
});
// Fade image
$('.item img').mouseover(function(){
$(this).parent().find('img:first').stop().animate({opacity:1}, 500);
})
$('.img_grayscale').mouseout(function(){
$(this).stop().animate({opacity:0}, 500);
});
});
// Grayscale w canvas method
function grayscale(src){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var imgObj = new Image();
imgObj.src = src;
canvas.width = imgObj.width;
canvas.height = imgObj.height;
ctx.drawImage(imgObj, 0, 0);
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
for(var y = 0; y < imgPixels.height; y++){
for(var x = 0; x < imgPixels.width; x++){
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
}
</script>
</head>
<body>
<div class='wrapper'>
<div class="item">
<img src="images/icondock.jpg" />
</div>
<div class="description">
<p class="description_content">The pack, the basic The pack, the basic More » </p>
</div>
</div>
<div class='wrapper'>
<div class="item">
<img src="images/koifish.jpg" />
</div>
<div class="description">
<p class="description_content">The pack, the basic The pack, the basic More » </p>
</div>
</div>
<div class='wrapper'>
<div class="item">
<img src="images/sakura.jpg" />
</div>
<div class="description">
<p class="description_content">The pack, the basic The pack, the basic More » </p>
</div>
</div>
</body>
</html>
if it is so hard you can use 2 images grayscale and color
javascript:
$(function(){
var canv = document.createElement('canvas'),
ctx = canv.getContext('2d');
canv.style.cssText = "position:absolute;left:-10000px;";
document.body.appendChild( canv );
function getGrayScale(src, el ){
$("<img src=\""+src+"\" />").appendTo("body").bind("load", function ( ) {
var w = canv.width = this.offsetWidth,
h = canv.height = this.offsetHeight;
ctx.drawImage( this, 0, 0);
var imgPixels = ctx.getImageData(0, 0, w, h);
for(var y = 0; y < imgPixels.height; y++){
for(var x = 0; x < imgPixels.width; x++){
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
$("<img class = \"img_grayscale\" src=\""+ canv.toDataURL() +"\" alt=\"\" />")
.insertBefore(el)
$(this).remove();
})
}
$(".item img").each(function(){
getGrayScale(this.src, $(this));
})
$(".item").delegate( ".img_grayscale", "mouseenter", function ( ) {
$(this).stop().animate({opacity:0}, 500)
}).delegate( ".img_grayscale","mouseout", function(){
$(this).stop().animate({opacity:1}, 500);
}).delegate( ".img_grayscale","click", function(){
$(this).remove();
});
});
add css:
.img_grayscale{ position:absolute;top:0;left:0;}
remove css:
.item img {opacity:0;}
i cant figure out what's wrong but this seems work as you expect

Categories