Html5 canvas animation leaves a trail - javascript

I'm trying to make a little game to play around with canvas. I've decided to go for Flappy Bird as there are plenty of examples online. My goal was to make the game "responsive" for all devices. If you open it in a mobile or whichever screen, you should be able to play it normally.
For this purpose I drew a background image within the canvas that will adapt the height to the screen's height and repeat it through the x-axis.
The issue I'm having is that, when I animate the bird, this one leaves a trail behind it.
As like so:
An easy fix would be clearing the canvas as explained in this post:
Canvas image leaves weird trail when moving left
But it isn't possible because of the way I'm painting my background (I paint it once and repaint it if it resizes).
Question
How do I avoid this image trail with a static background? Is it maybe possible to have like a false static background that doesn't need to be repainted?
I obviously want to do it in the canvas, without needing to have an image in the html.
This is the code with the main functionality so that you can take a look:
const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");
cvs.style.height = "100vh";
cvs.style.width = "100vw";
var bird = new Image();
var bg = new Image();
bird.src = "https://lh3.googleusercontent.com/prntPuix7QxlhKXx6IBtTxv7PrdEJtmzFJ4mopScNS1_klze86BVNy3PqHbQn2UQ4JyJdix3XQ=w128-h128-e365";
bg.src = "https://opengameart.org/sites/default/files/bg_5.png";
let gravity = 1;
birdPositionY = 10;
birdPositionX = 50;
const draw = () => {
ctx.drawImage(bird, birdPositionX, birdPositionY);
birdPositionY += gravity;
birdPositionX += 3;
requestAnimationFrame(draw);
};
const resizeCanvas = () => {
const {
width,
height
} = cvs.getBoundingClientRect();
cvs.height = height;
cvs.width = width;
let x = 0,
y = 0;
while (x < cvs.width && y < cvs.height) {
ctx.drawImage(bg, x, y, 360, cvs.height);
x += bg.width;
}
};
bg.onload = () => {
resizeCanvas();
};
window.addEventListener("resize", resizeCanvas, false);
draw();
<!DOCTYPE html>
<html>
<head>
<title>Flappy Bird</title>
<meta name="viewport" content="width=device-width, user-scalable=no" />
<style>
html {
overflow: hidden;
}
body {
margin: 0;
}
canvas {
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="index.js"></script>
</body>
</html>
Hope it did make sense!
Thanks in advance!

Draw your background on a canvas that you will keep off-screen, then draw this canvas every frame on your visible one before you draw your moving parts.
const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");
// our backround canvas that we won't append in the doc ("off-screen")
const background = cvs.cloneNode();
const bg_ctx = background.getContext('2d');
cvs.style.height = "100vh";
cvs.style.width = "100vw";
var bird = new Image();
var bg = new Image();
bird.src = "https://lh3.googleusercontent.com/prntPuix7QxlhKXx6IBtTxv7PrdEJtmzFJ4mopScNS1_klze86BVNy3PqHbQn2UQ4JyJdix3XQ=w128-h128-e365";
bg.src = "https://opengameart.org/sites/default/files/bg_5.png";
let gravity = 1;
birdPositionY = 10;
birdPositionX = 50;
const draw = () => {
// first draw the background canvas
ctx.drawImage(background, 0,0);
// then your persona
ctx.drawImage(bird, birdPositionX, birdPositionY);
birdPositionY += gravity;
birdPositionX += 3;
requestAnimationFrame(draw);
};
const resizeCanvas = () => {
const {
width,
height
} = cvs.getBoundingClientRect();
// resize both canvases
cvs.height = background.height = height;
cvs.width = background.width = width;
let x = 0,
y = 0;
while (x < cvs.width && y < cvs.height) {
// draw on the off-screen canvas
bg_ctx.drawImage(bg, x, y, 360, cvs.height);
x += bg.width;
}
};
bg.onload = () => {
resizeCanvas();
draw();
};
window.addEventListener("resize", resizeCanvas, false);
<!DOCTYPE html>
<html>
<head>
<title>Flappy Bird</title>
<meta name="viewport" content="width=device-width, user-scalable=no" />
<style>
html {
overflow: hidden;
}
body {
margin: 0;
}
canvas {
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="index.js"></script>
</body>
</html>

I think you could just call resizeCanvas in your draw loop to redraw the background.
EDIT: Apparently that does not work. Another option is just drawing it in the draw loop like this:
const draw = () => {
ctx.clearRect(0, 0, cvs.width, cvs.height)
let x = 0, y = 0;
while (x < cvs.width && y < cvs.height) {
ctx.drawImage(bg, x, y, 360, cvs.height);
x += bg.width;
}
ctx.drawImage(bird, birdPositionX, birdPositionY);
birdPositionY += gravity;
birdPositionX += 3;
requestAnimationFrame(draw);
};
Edit: That did not work either. The other option would be to make two canvases and overlap them with one drawing the background and one drawing the bird.

Related

how to create pixelated video with pure java script

I am trying to create a blurred face video (when there were squares)
everything is ok until I minimize the size of the square then it becomes so laggy
and slow even some times the video stop working for example when the blur = 1 ;
this is my code :
<!DOCTYPE html>
<html>
<head>
<style>
#canvas{
width: 400px;
}
</style>
</head>
<body>
<video id="video" controls width="300" height="300"></video>
<canvas id="canvas" width="1280" height="720" ></canvas>
<script>
// Get references to the video and canvas elements
var video = document.getElementById("video");
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var videoSource = "111.mp4" ;
video.src = videoSource;
video.addEventListener("play", function() {
drawVideo();
});
function drawVideo() {
context.drawImage(video, 0, 0);
let blur = 20 ;
let originalImageData = context.getImageData( 0, 0, canvas.width, canvas.height ).data;
for (let y = 0; y < canvas.height; y += blur) {
for (let x = 0; x < canvas.width; x += blur) {
const pixelIndexPosition = (x + y * canvas.width) * 4;
context.fillStyle = `rgba(
${originalImageData[pixelIndexPosition]},
${originalImageData[pixelIndexPosition + 1]},
${originalImageData[pixelIndexPosition + 2]},
${originalImageData[pixelIndexPosition + 3]})`;
context.fillRect(x, y, blur, blur);
}
}
// Continue to draw the video
if (video.paused || video.ended) {
return;
}
requestAnimationFrame(drawVideo);
}
</script>
</body>
</html>

Saturate image where mouse is hovering

I'm trying to have an image on my website become saturated at the same location the mouse is. When the mouse moves the saturation effect goes with it, and the area previously hovered over becomes grayscale again. I'm thinking this effect could be accomplished using saturate(), however I haven't had any success with it. Additionally, I would like the effect to be circular without hard edges similar to this.
Example of what it would look like (orange arrow indicating where the mouse is).
Any help or insight would be appreciated, thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content= "width=device-width, initial-scale=1.0" />
</head>
<script>
const size = 250;
var radius = 30;
var rad = Math.PI / 180;
var canvas = document.querySelector("canvas")
var ctx = canvas.getContext("2d");
canvas.width = size;
canvas.height = size;
var image = new Image();
image.onload = demo
image.src = "https://picsum.photos/250"
function draw_circle(x, y, radius) {
ctx.clearRect(0, 0, size, size);
ctx.drawImage(image, 0, 0); // image to change
ctx.globalCompositeOperation = "saturation";
ctx.beginPath();
ctx.fillStyle = "hsl(0,100%,50%)"; // saturation at 100%
ctx.arc(x, y, radius, 0, 360 * rad, false);
ctx.fill()
ctx.closePath();
ctx.globalCompositeOperation = "source-over"; // restore default comp
}
function demo() {
ctx.drawImage(image, 0, 0); // image to change
canvas.addEventListener('mousemove', function(ev) {
var cx = ev.offsetX
var cy = ev.offsetY
draw_circle(cx, cy, radius)
})
}
</script>
<canvas></canvas>
</html>
Using a canvas we can try. Here's a start inspired by How can I adjust the huse, saturation, and lightness of in image in HTML5 Canvas?.
const size = 250;
var radius = 30;
var rad = Math.PI / 180;
var canvas = document.querySelector("canvas")
var ctx = canvas.getContext("2d");
canvas.width = size;
canvas.height = size;
var image = new Image();
image.onload = demo
image.src = "https://picsum.photos/250"
function draw_circle(x, y, radius) {
ctx.clearRect(0, 0, size, size);
ctx.drawImage(image, 0, 0); // image to change
ctx.globalCompositeOperation = "saturation";
ctx.beginPath();
ctx.fillStyle = "hsl(0,100%,50%)"; // saturation at 100%
ctx.arc(x, y, radius, 0, 360 * rad, false);
ctx.fill()
ctx.closePath();
ctx.globalCompositeOperation = "source-over"; // restore default comp
}
function demo() {
ctx.drawImage(image, 0, 0); // image to change
canvas.addEventListener('mousemove', function(ev) {
var cx = ev.offsetX
var cy = ev.offsetY
draw_circle(cx, cy, radius)
})
}
<canvas></canvas>
This is a simple answer (change the logic of the program as you want):
<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
width: 200px;
height: 150px;
}
.image {
width: 100%;
height: 100%;
}
</style>
<script>
const width = 50;
const height = 50;
function create() {
const element = document.createElement("div");
element.id = "filtered";
element.style.width = `${width}px`;
element.style.height = `${height}px`;
element.style.borderRadius = "50%";
element.style.position = "absolute";
element.style.backgroundColor = "red";
element.style.opacity = "0.2";
element.style.zIndex = "2";
return element;
}
function changePos(e) {
x = e.clientX;
y = e.clientY;
let element = document.getElementById("filtered");
if (!element) {
element = create();
document.getElementById("focusArea").appendChild(element);
}
element.style.left = `${x - width / 2}px`;
element.style.top = `${y - height / 2}px`;
}
function removeElement() {
if (document.getElementById("filtered")) {
document.getElementById("filtered").remove();
}
}
</script>
</head>
<body>
<div
id="focusArea"
onmouseleave="removeElement()"
onmousemove="changePos(event)"
class="relative"
>
<img
src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/800px-Image_created_with_a_mobile_phone.png"
class="image"
/>
</div>
</body>
</html>

Why does my game character keep accelerating when I use the keydown event?

I am trying to make a simple game. The green block is my game character. I used a the keydown event to make my character able to move right and left. When I hold down the right or left arrow key, the character keeps on accelerating. If you start by tapping the right or left arrow key, you will see that the space interval between where the character was and where it is increases as you click more. How can I make my character move at a constant speed with constant space intervals.
//variables
var canvas = document.getElementById("canvas");
var draw = canvas.getContext("2d");
var characterx = 20;
var charactery = window.innerHeight - 60;
var dx = 0.01;
var dy = 0.01;
//canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//main game function
function run() {
//loops the function
requestAnimationFrame(run);
//clears the screen
draw.clearRect(0, 0, canvas.width, canvas.height)
//draws the ground
draw.beginPath();
draw.fillStyle = "#823819";
draw.fillRect(0, canvas.height - 20, canvas.width, 20);
draw.fill();
draw.closePath();
//draws the main character
draw.beginPath();
draw.fillStyle = "#128522";
draw.fillRect(characterx, charactery, 40, 40);
draw.fill();
draw.closePath();
//key evevnts
window.addEventListener("keydown",function(event) {
if(event.keyCode == 39) {
characterx += dx;
}
});
window.addEventListener("keydown",function(event) {
if(event.keyCode == 37) {
characterx -= dx;
}
});
};
run();
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style type="text/css">
body {
margin: 0;
overflow: hidden;
}
canvas {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Your event listeners should be added outside of your game loop.
Currently you are adding an extra listener for each keypress on every frame, meaning that on the first frame you will move dx * 1 for a keypress, but on frame 100 you will move dx * 100 for a single keypress.
This is also why your dx value had to be so low - I've increased it in the sample below, but you can adjust it as needed.
//variables
var canvas = document.getElementById("canvas");
var draw = canvas.getContext("2d");
var characterx = 20;
var charactery = window.innerHeight - 60;
var dx = 3.0;
var dy = 3.0;
//canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//key evevnts
window.addEventListener("keydown",function(event) {
if(event.keyCode == 39) {
characterx += dx;
}
});
window.addEventListener("keydown",function(event) {
if(event.keyCode == 37) {
characterx -= dx;
}
});
//main game function
function run() {
//loops the function
requestAnimationFrame(run);
//clears the screen
draw.clearRect(0, 0, canvas.width, canvas.height)
//draws the ground
draw.beginPath();
draw.fillStyle = "#823819";
draw.fillRect(0, canvas.height - 20, canvas.width, 20);
draw.fill();
draw.closePath();
//draws the main character
draw.beginPath();
draw.fillStyle = "#128522";
draw.fillRect(characterx, charactery, 40, 40);
draw.fill();
draw.closePath();
};
run();
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style type="text/css">
body {
margin: 0;
overflow: hidden;
}
canvas {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

Repeating image in a canvas with responsive height

I'm trying to create a canvas where I have an image as a background that repeats horizontally and adapts the height automatically.
I've managed to repeat the background image following the x-axis but I'm unable to make the height responsive.
This is my code so far:
const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");
const bg = new Image();
bg.src = "http://lorempixel.com/100/100";
const draw = () => {
const ptrn = ctx.createPattern(bg, "repeat-x");
ctx.fillStyle = ptrn;
ctx.fillRect(0, 0, canvas.width, canvas.height);
requestAnimationFrame(draw);
};
draw();
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<canvas id="canvas" width="1000" height="200"></canvas>
<script src="index.js"></script>
</body>
</html>
TLDR: I would like to be able to have an image within my canvas that repeats horizontally and its height is responsive.
Thanks in advance.
Hopefully the explanation in the comments answers your question. Feel free to ask for clarification.
const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");
// First stretch the canvas so we can get
// the full size of teh browser window
cvs.style.height = '100vh';
cvs.style.width = '100vw';
// Now adjust actual canvas size to match
const {width, height} = cvs.getBoundingClientRect();
cvs.height = height;
cvs.width = width;
const bg = new Image();
// Should always wait for onload
// before drawing to prevent race condition.
bg.onload = ()=>{
var x=0;
while(x < cvs.width){
ctx.drawImage(bg, x, 0, 100, cvs.height);
x += bg.width;
}
// draw the image a bunch of times
// var x=0, y=0;
// while(x < cvs.width && y < cvs.height){
// ctx.drawImage(bg, x, y);
// x += bg.width;
// if(x > cvs.width){
// x = 0;
// y += bg.height;
// }
// }
};
bg.src = "http://lorempixel.com/100/100";
<canvas id="canvas"></canvas>
<script src="index.js"></script>
If I got it right you want to fill the height and repeat horizontally, is that correct?
const cvs = document.getElementById("canvas");
const ctx = cvs.getContext("2d");
var bg = new Image();
bg.src = "http://lorempixel.com/100/100";
var tempCanvas = document.createElement("canvas"),
tCtx = tempCanvas.getContext("2d");
var imgWidth = 200;
var imgHeight = 200;
const draw = () => {
tempCanvas.width = imgWidth;
tempCanvas.height = imgHeight;
tCtx.drawImage(bg, 0, 0, 100, 100, 0, 0, imgWidth, imgHeight);
const ptrn = ctx.createPattern(tempCanvas , "repeat-x");
ctx.fillStyle = ptrn;
ctx.fillRect(0, 0, canvas.width, canvas.height);
requestAnimationFrame(draw);
};
bg.onload = () => {
draw();
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<canvas id="canvas" width="1000" height="200"></canvas>
<script src="index.js"></script>
</body>
</html>
try setting up the image size to match the canvas size just like that:
bg.src = "http://lorempixel.com/200/200";
Cheers! :)

drawImage() not working consistently

When you put a picture named logo.png in the same directory as this html file and try to run it in a web browser the picture only appears 1 times out of 10 refreshes in IE and doesn't appear the first time in Firefox but does appear after further refreshes.
What the heck is going on ?
(drawImage() method is called in the showIntro() function)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Example 1 - Title Screen</title>
<script>
window.onload = function () {
var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var State = {
_current: 0,
INTRO: 0,
LOADING: 1,
LOADED: 2
}
window.addEventListener('click', handleClick, false);
window.addEventListener('resize', doResize, false);
doResize();
function handleClick() {
State._current = State.LOADING;
fadeToWhite();
}
function doResize() {
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
switch (State._current) {
case State.INTRO:
showIntro();
break;
}
}
function fadeToWhite(alphaVal) {
// If the function hasn't received any parameters, start with 0.02
var alphaVal = (alphaVal == undefined) ? 0.02 : parseFloat(alphaVal) + 0.02;
// Set the color to white
c.fillStyle = '#FFFFFF';
// Set the Global Alpha
c.globalAlpha = alphaVal;
// Make a rectangle as big as the canvas
c.fillRect(0, 0, canvas.width, canvas.height);
if (alphaVal < 1.0) {
setTimeout(function () {
fadeToWhite(alphaVal);
}, 30);
}
}
function showIntro() {
var phrase = "Click or tap the screen to start the game";
// Clear the canvas
c.clearRect(0, 0, canvas.width, canvas.height);
// Make a nice blue gradient
var grd = c.createLinearGradient(0, canvas.height, canvas.width, 0);
grd.addColorStop(0, '#ceefff');
grd.addColorStop(1, '#52bcff');
c.fillStyle = grd;
c.fillRect(0, 0, canvas.width, canvas.height);
var logoImg = new Image();
logoImg.src = './logo.png';
// Store the original width value so that we can keep
// the same width/height ratio later
var originalWidth = logoImg.width;
// Compute the new width and height values
logoImg.width = Math.round((50 * document.body.clientWidth) / 100);
logoImg.height = Math.round((logoImg.width * logoImg.height) / originalWidth);
// Create an small utility object
var logo = {
img: logoImg,
x: (canvas.width / 2) - (logoImg.width / 2),
y: (canvas.height / 2) - (logoImg.height / 2)
}
// Present the image
c.drawImage(logo.img, logo.x, logo.y, logo.img.width, logo.img.height);
// Change the color to black
c.fillStyle = '#000000';
c.font = 'bold 16px Arial, sans-serif';
var textSize = c.measureText(phrase);
var xCoord = (canvas.width / 2) - (textSize.width / 2);
c.fillText(phrase, xCoord, (logo.y + logo.img.height) + 50);
}
}
</script>
<style type="text/css" media="screen">
html { height: 100%; overflow: hidden }
body {
margin: 0px;
padding: 0px;
height: 100%;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="100" height="100">
Your browser doesn't include support for the canvas tag.
</canvas>
</body>
</html>
The problem is that you aren't waiting for the image to load when you call drawImage().
You could use something like:
logo.img.onload = function(){
c.drawImage(logo.img, logo.x, logo.y, logo.img.width, logo.img.height);
};
Although make sure you don't start modifying the canvas until this has happened.

Categories