Get the image onto the canvas - javascript

I need to upload the image onto the canvas, but the image keeps on coming beside the canvas instead of inside it. I made a code for that to happen but does not work. Thanks in advance.
Js:
//Link Canvas
var canvas = document.getElementById('gameCanvas');
var context = canvas.getContext('2d');
var width = $('#gameCanvas').width();
var height = $('#gameCanvas').height();
//Car Image
var car = new Image();
car.src = "http://images.clipartpanda.com/car-top-view-clipart-red-racing-car-top-view-fe3a.png";
//Car x,y Position
var x = 220;
var y = 200;
//Car Speed and angle
var speed = 7;
var angle = 0;
var mod = 0;
//Keyboard Listeners
window.addEventListener("keydown", keypress_handler, false);
window.addEventListener("keyup", keyup_handler, false);
var moveInterval = setInterval(function () {
draw();
}, 30);
//Draw Car
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
//Rotate Car When Turning
x += (speed * mod) * Math.cos(Math.PI / 180 * angle);
y += (speed * mod) * Math.sin(Math.PI / 180 * angle);
context.save();
context.translate(x, y);
context.rotate(Math.PI / 180 * angle);
context.drawImage(car, -(car.width / 2), -(car.height / 2));
context.restore();
}
//Keyboard Function
function keyup_handler(event) {
console.log('a');
if (event.keyCode == 38 || event.keyCode == 40) {
mod = 0;
}
}
//Keyboard keys to operate car
function keypress_handler(event) {
console.log(event.keyCode);
if (event.keyCode == 38) { //Up arrow
mod = 1;
}
if (event.keyCode == 40) { //Down arrow
mod = -1;
}
if (event.keyCode == 37) { //Left Arrow
angle -= 5;
}
if (event.keyCode == 39) { //Right Arrow
angle += 5;
}
}
function update() {
window.requestAnimationFrame(update);
x += speed;
y += speed;
if (x >= $('#gameCanvas')){
speed = 0;
}
if (y >= $('#gameCanvas')){
speed = -1.0 * speed;
speed = 0;
}
}
Code That does not work:
var URL = [
"http://thumb101.shutterstock.com/display_pic_with_logo/69386/69386,1162932792,3/stock-photo-lone-car-in-four-lanes-from-above-2128171.jpg",
];
var canvas
var imgs = URL.map(function(URL) {
var img = new Image();
img.src = URL;
document.body.appendChild(img);
return img;
});

var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
var background = new Image();
background.src = "http://thumb101.shutterstock.com/display_pic_with_logo/69386/69386,1162932792,3/stock-photo-lone-car-in-four-lanes-from-above-2128171.jpg";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}​

var background = new Image();
background.src = "http://thumb101.shutterstock.com/display_pic_with_logo/69386/69386,1162932792,3/stock-photo-lone-car-in-four-lanes-from-above-2128171.jpg";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
context.drawImage(background,0,0);
}

Related

How can I reverse the direction of this square after it reaches a certain value?

I'm trying to create an idle animation where the red rectangle moves back and forth slightly in a loop. For some reason once it reaches the specified threshhold instead of proceeding to move in the opposite direction, it just stops.
What did I do wrong?
<canvas id="myCanvas" width="1500" height="500" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Spaceship structure
var shipWidth = 250;
var shipHeight = 100;
// Canvas parameters
var cWidth = canvas.width;
var cHeight = canvas.height;
// Positioning variables
var centerWidthPosition = (cWidth / 2) - (shipWidth / 2);
var centerHeightPosition = (cHeight / 2) - (shipHeight / 2);
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function drawShip(){
ctx.clearRect(0, 0, cWidth, cHeight);
ctx.fillStyle = "#FF0000";
ctx.fillRect(centerWidthPosition,centerHeightPosition,shipWidth,shipHeight);
centerWidthPosition--;
if (centerWidthPosition < 400){
++centerWidthPosition;
}
requestAnimationFrame(drawShip);
}
drawShip();
</script>
#TheAmberlamps explained why it's doing that. Here I offer you a solution to achieve what I believe you are trying to do.
Use a velocity variable that changes magnitude. X position always increases by velocity value. Velocity changes directions at screen edges.
// use a velocity variable
var xspeed = 1;
// always increase by velocity
centerWidthPosition += xspeed;
// screen edges are 0 and 400 in this example
if (centerWidthPosition > 400 || centerWidthPosition < 0){
xspeed *= -1; // change velocity direction
}
I added another condition in your if that causes the object to bounce back and forth. Remove the selection after || if you don't want it doing that.
Your function is caught in a loop; once centerWidthPosition reaches 399 your conditional makes it increment back up to 400, and then it decrements back to 399.
here is another one as a brain teaser - how would go by making this animation bounce in the loop - basically turn text into particles and then reverse back to text and reverse back to particles and back to text and so on and on and on infinitely:
var random = Math.random;
window.onresize = function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
window.onresize();
var ctx = canvas.getContext('2d');
ctx.font = 'bold 50px "somefont"';
ctx.textBaseline = 'center';
ctx.fillStyle = 'rgba(255,255,255,1)';
var _particles = [];
var particlesLength = 0;
var currentText = "SOMETEXT";
var createParticle = function createParticle(x, y) {_particles.push(new Particle(x, y));};
var checkAlpha = function checkAlpha(pixels, i) {return pixels[i * 4 + 3] > 0;};
var createParticles = function createParticles() {
var textSize = ctx.measureText(currentText);
ctx.fillText(currentText,Math.round((canvas.width / 2) - (textSize.width / 2)),Math.round(canvas.height / 2));
var imageData = ctx.getImageData(1, 1, canvas.width, canvas.height);
var pixels = imageData.data;
var dataLength = imageData.width * imageData.height;
for (var i = 0; i < dataLength; i++) {
var currentRow = Math.floor(i / imageData.width);
var currentColumn = i - Math.floor(i / imageData.height);
if (currentRow % 2 || currentColumn % 2) continue;
if (checkAlpha(pixels, i)) {
var cy = ~~(i / imageData.width);
var cx = ~~(i - (cy * imageData.width));
createParticle(cx, cy);
}}
particlesLength = _particles.length;
};
var Point = function Point(x, y) {
this.set(x, y);
};
Point.prototype = {
set: function (x, y) {
x = x || 0;
y = y || x || 0;
this._sX = x;
this._sY = y;
this.reset();
},
add: function (point) {
this.x += point.x;
this.y += point.y;
},
multiply: function (point) {
this.x *= point.x;
this.y *= point.y;
},
reset: function () {
this.x = this._sX;
this.y = this._sY;
return this;
},
};
var FRICT = new Point(0.98);//set to 0 if no flying needed
var Particle = function Particle(x, y) {
this.startPos = new Point(x, y);
this.v = new Point();
this.a = new Point();
this.reset();
};
Particle.prototype = {
reset: function () {
this.x = this.startPos.x;
this.y = this.startPos.y;
this.life = Math.round(random() * 300);
this.isActive = true;
this.v.reset();
this.a.reset();
},
tick: function () {
if (!this.isActive) return;
this.physics();
this.checkLife();
this.draw();
return this.isActive;
},
checkLife: function () {
this.life -= 1;
this.isActive = !(this.life < 1);
},
draw: function () {
ctx.fillRect(this.x, this.y, 1, 1);
},
physics: function () {
if (performance.now()<nextTime) return;
this.a.x = (random() - 0.5) * 0.8;
this.a.y = (random() - 0.5) * 0.8;
this.v.add(this.a);
this.v.multiply(FRICT);
this.x += this.v.x;
this.y += this.v.y;
this.x = Math.round(this.x * 10) / 10;
this.y = Math.round(this.y * 10) / 10;
}
};
var nextTime = performance.now()+3000;
createParticles();
function clearCanvas() {
ctx.fillStyle = 'rgba(0,0,0,1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
(function clearLoop() {
clearCanvas();
requestAnimationFrame(clearLoop);
})();
(function animLoop(time) {
ctx.fillStyle = 'rgba(255,255,255,1)';
var isAlive = true;
for (var i = 0; i < particlesLength; i++) {
if (_particles[i].tick()) isAlive = true;
}
requestAnimationFrame(animLoop);
})();
function resetParticles() {
for (var i = 0; i < particlesLength; i++) {
_particles[i].reset();
}}

Square on my canvas appears for a second and then disappears

This is a whole project so if there are constraints or variables not used, ignore them.
const WIDTH = 640;
const HEIGHT = 480;
const PLAYER_SIZE = 20;
const REPAINT_DELAY = 50;
const EASY_DELAY = 1750;
const MODERATE_DELAY = 1000;
const HARD_DELAY = 750;
const MAX_BLOCKS = 100;
var canvas;
var ctx;
var playerX = 310;
var playerY = 230;
var DX = 0;
var DY = 0;
window.onload = init;
function clearCanvas() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
ctx.fillStyle = "#0000FF";
ctx.fillRect(playerX, playerY, PLAYER_SIZE, PLAYER_SIZE);
window.onkeydown = keyArrows;
return setInterval(draw, 10);
}
function draw() {
clearCanvas();
/*
** I think this is where something is going wrong.
** I tried moving around the `clearCanvas()` but that didn’t work.
** It just made the whole square not show up at all.
*/
if (playerX + DX > WIDTH || playerX + DX < 0)
DX = 0;
if (playerY + DY > HEIGHT || playerY + DY < 0)
DY = 0;
DX += playerX;
DY += playerY;
}
function keyArrows(e) {
if (e.keyCode == 37) {
DX = -5;
DY = 0;
} else if (e.keyCode == 38) {
DX = 0;
DY = -5;
} else if (e.keyCode == 39) {
DX = 5;
DY = 0;
} else if (e.keyCode == 40) {
DX = 0;
DY = 5;
}
}
init();
I’m trying to get the blue square to move. Would this code even work to make the square move around once it’s actually drawn?

Remove background in canvas game

I am trying to learn JavaScript and found this tutorial:
http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/
But i can not figure out how to remove the background from the game.
Any help with removing the background would be appreciated! :)
Code that affects the background:
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "images/background.png";
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
The whole JavaScript file:
http://www.lostdecadegames.com/demos/simple_canvas_game/js/game.js
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "images/background.png";
// Hero image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
heroReady = true;
};
heroImage.src = "images/hero.png";
// Monster image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
monsterReady = true;
};
monsterImage.src = "images/monster.png";
// Game objects
var hero = {
speed: 256 // movement in pixels per second
};
var monster = {};
var monstersCaught = 0;
// Handle keyboard controls
var keysDown = {};
addEventListener("keydown", function (e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);
// Reset the game when the player catches a monster
var reset = function () {
hero.x = canvas.width / 2;
hero.y = canvas.height / 2;
// Throw the monster somewhere on the screen randomly
monster.x = 32 + (Math.random() * (canvas.width - 64));
monster.y = 32 + (Math.random() * (canvas.height - 64));
};
// Update game objects
var update = function (modifier) {
if (38 in keysDown) { // Player holding up
hero.y -= hero.speed * modifier;
}
if (40 in keysDown) { // Player holding down
hero.y += hero.speed * modifier;
}
if (37 in keysDown) { // Player holding left
hero.x -= hero.speed * modifier;
}
if (39 in keysDown) { // Player holding right
hero.x += hero.speed * modifier;
}
// Are they touching?
if (
hero.x <= (monster.x + 32)
&& monster.x <= (hero.x + 32)
&& hero.y <= (monster.y + 32)
&& monster.y <= (hero.y + 32)
) {
++monstersCaught;
reset();
}
};
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (heroReady) {
ctx.drawImage(heroImage, hero.x, hero.y);
}
if (monsterReady) {
ctx.drawImage(monsterImage, monster.x, monster.y);
}
// Score
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "24px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Goblins caught: " + monstersCaught, 32, 32);
};
// The main game loop
var main = function () {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
// Request to do this again ASAP
requestAnimationFrame(main);
};
// Cross-browser support for requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
// Let's play this game!
var then = Date.now();
reset();
main();
Just empty the image source:
bgImage.src='';
Then...
bgImage.onload will never execute,
bgReady will always be false,
if (bgReady){ ctx.drawImage(bgImage, 0, 0); } will never execute,
Your background will remain transparent!

Canvas Asteroids game

I'm making Asteroids game in html5 with canvas. I've made moveable ship, which can rotate right and left and can move forward. I've added friction to slow it down when keys aren't pressed. Next thing to do is shooting bullets/lasers. I have yet only one shot and bullet goes forward, but it follow the movement of ship too :/ I don't know how to detach it from the ship and how to make more bullets.
Here's the code:
window.addEventListener('keydown',doKeyDown,true);
window.addEventListener('keyup',doKeyUp,true);
var canvas = document.getElementById('pageCanvas');
var context = canvas.getContext('2d');
var angle = 0;
var H = window.innerHeight; //*0.75,
var W = window.innerWidth; //*0.75;
canvas.width = W;
canvas.height = H;
var xc = W/2; //zeby bylo w centrum :v
var yc = H/2; //jw.
var x = xc;
var y = yc;
var dv = 0.2;
var dt = 1;
var vx = 0;
var vy = 0;
var fps = 30;
var maxVel = 10;
var frict = 0.99;
var brakes = 0.90;
var keys = new Array();
var fire = false;
var laser = false;
///////////////////lasery xD
var lx = 25,
ly = 9,
lw = 4,
lh = 4;
function doKeyUp(evt){
keys[evt.keyCode] = false;
fire = false;
}
function doKeyDown(evt){
keys[evt.keyCode] = true;
}
//OOOOOOOOOOOOOOOOOOLASEROOOOOOOOOOOOOOOOOOOOOOOOOOO
function drawLaser() {
context.fillStyle = "red";
context.fillRect(lx,ly,lw,lh);
}
function moveLaser() {
lx += 2;
}
//OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
function ogienZdupy(){
context.fillStyle = "red";
context.beginPath();
context.moveTo(-2,2);
context.lineTo(2,10);
context.lineTo(-2,18);
context.lineTo(-25,10);
context.lineTo(-2,2);
context.strokeStyle = "red";
context.stroke();
}
function convertToRadians(degree) {
return degree*(Math.PI/180);
}
function incrementAngle() {
angle += 5;
if(angle > 360){
angle = 0;
}
}
function decrementAngle(){
angle -= 5;
if(angle > 360){
angle = 0;
}
}
function xyVelocity(){
vx += dv * Math.cos(convertToRadians(angle)); //* friction;
vy += dv * Math.sin(convertToRadians(angle)); //* friction;
if(vx > maxVel){
vx = maxVel;
}
if(vy > maxVel){
vy = maxVel;
}
}
function shipMovement(){
if(38 in keys && keys[38]){
xyVelocity();
fire = true;
}
if(40 in keys && keys[40]){
vx = 0;
vy = 0;
}
if(37 in keys && keys[37]){
decrementAngle();
};
if (39 in keys && keys[39]){
incrementAngle();
};
if (32 in keys && keys[32]){
laser = true;
};
}
function xyAndFriction(){
x += vx * dt;
y += vy * dt;
vx *= frict;
vy *= frict;
}
function outOfBorders(){
if(x > W){
x = x - W;
}
if(x< 0){
x = W;
}
if(y > H){
y = y - H;
}
if(y < 0){
y = H;
}
}
function blazeatron420(){
context.beginPath();
context.moveTo(0,0);
context.lineTo(20,10);
context.lineTo(0,20);
context.lineTo(7,10);
context.lineTo(0,0);
context.strokeStyle = "green";
context.stroke();
}
function space(){
context.fillStyle = "black";
context.fillRect(0,0,W,H);
}
function drawEverything() {
shipMovement();
xyAndFriction();
outOfBorders();
//context.save();
space();
context.save();
context.translate(x,y);
//context.translate(25,25);
context.rotate(convertToRadians(angle));
context.translate(-7,-10);
if(fire){
ogienZdupy();
}
if(laser){
drawLaser();
moveLaser();
}
context.fillStyle = "green";
//context.fillText(vx + " km/h",50,50);
/*context.fillText("dupa",-30,0);
context.beginPath();
context.moveTo(-20,5);
context.lineTo(-5,10);
context.strokeStyle = "green"; //KOLOR LINII ;_;
context.stroke();*/
blazeatron420();
context.restore();
}
setInterval(drawEverything, 20);
And the fiddle http://jsfiddle.net/tomasthall/q40zvd6v/1/
I moved your laser drawing out of the rotated context.
Initiated lx and ly to x y in the moment of firing.
laser = true;
lx = x;
ly = y;
http://jsfiddle.net/q40zvd6v/2/
Now you need to just give the laser a proper vector.
That can be calculated from the angle of your ship and some trigonometry.
if (32 in keys && keys[32]){
laser = true;
lx = x;
ly = y;
var angle_in_radians = convertToRadians(angle);
lvx = Math.cos(angle_in_radians);
lvy = Math.sin(angle_in_radians);
};
And it shoots fine now:
http://jsfiddle.net/q40zvd6v/4/
Looks much nicer if you add the ship vector to projectile vector though.
if (32 in keys && keys[32]){
laser = true;
lx = x;
ly = y;
var angle_in_radians = convertToRadians(angle);
lvx = Math.cos(angle_in_radians);
lvy = Math.sin(angle_in_radians);
lvx += vx;
lvy += vy;
};
http://jsfiddle.net/q40zvd6v/5/
Good luck on your game :>
this be your problem right here:
context.rotate(convertToRadians(angle));
context.translate(-7,-10);
you rotate everything on the canvas..
when in fact you should only be rotating the blazeatron420
Please look at this question:
How do I rotate a single object on an html 5 canvas?
and see the solutions for rotating a single "object"..

how to move an image on canvas using keyboard arrow key in html5

I m Drawing the image on canvas with this code
and it successfully draw the image on canvas now i want to move the image on canvas for that i write the code i check that if the right key of my keyboard is pressed i will increment the x coordinate of an image if left key is pressed i will decrement the x coordinate but image is not moving on the canvas
player = new Image();
player.src = "game_character.png";
context.drawImage(player,player.x * wallDim + wallDim ,player.y * wallDim + wallDim ,50,50);
how to move an image on canvas
var handleInput = function(event, keyState) {
switch(event.which) {
case 37: { // Left Arrow
keyDown.arrowLeft = keyState;
break;
}
case 38: { // Up Arrow
keyDown.arrowUp = keyState;
break;
}
case 39: { // Right Arrow
keyDown.arrowRight = keyState;
break;
}
case 40: { // Down Arrow
keyDown.arrowDown = keyState;
break;
}
}
}
/**
* physics
*
* This function contains the basic logic for the maze.
*/
var physics = function() {
console.log("physics ");
console.log("first condition "+keyDown.arrowRight +player.x+1);
if(keyDown.arrowLeft && player.x-1 >= 0 && map[player.y][player.x-1] != 1) {
player.x--;
redraw = true;
}
if(keyDown.arrowUp && player.y-1 >= 0 && map[player.y-1][player.x] != 1) {
player.y--;
redraw = true;
}
if(keyDown.arrowRight && player.x+1 < map[0].length && map[player.y][player.x+1] != 1) {
console.log("arrow right");
player.x++;
redraw = true;
}
if(keyDown.arrowDown && player.y+1 < map.length && map[player.y+1][player.x] != 1) {
player.y++;
redraw = true;
}
if(keyDown.arrowRight && player.x+1 >= map[0].length)
{
player.x++;
document.getElementById("canvas_div").style.display="none";
document.getElementById("end_screen_div").style.display="block";
//alert("completed");
}
}
/**
* draw
*
* This function simply draws the current state of the game.
*/
var draw = function() {
// Don't redraw if nothing has changed
if(!redraw)
return;
context.clearRect(0, 0, cols, rows);
context.beginPath();
// Draw the maze
for(var a = 0; a < rows; a++) {
for(var b = 0; b < cols; b++) {
switch(map[a][b]) {
case C.EMPTY: context.fillStyle = colors.empty; break;
case C.WALL: context.fillStyle = colors.wall; break;
}
context.fillRect(b * wallDim, a * wallDim, wallDim, wallDim); // x, y, width, height
}
}
// Draw the player
/* context.fillStyle = colors.player;
context.arc(
player.x * wallDim + wallDim / 2, // x position
player.y * wallDim + wallDim / 2, // y position
wallDim / 2, // Radius
0, // Starting angle
Math.PI * 2, // Ending angle
true // antiClockwise
);*/
player = new Image();
player.src = "game_character.png";
context.drawImage(player,player.x * wallDim + wallDim ,player.y * wallDim + wallDim ,50,50);
var firstplayer=new Image();
firstplayer.src="top_character01.png";
context.drawImage(firstplayer,680,0,60,60);
var secondplayer= new Image();
secondplayer.src="top_character02.png";
context.drawImage(secondplayer,750,0,60,60);
context.fill();
context.closePath();
redraw = false;
}
In your draw method, you reinitialize the player each time :
player = new Image();
player.src = "game_character.png";
So you erase the player.x modified by your event handler.
You should initialize the player only once, outside the draw function. You can move the initialization like this :
var player = new Image();
player.src = "game_character.png";
var draw = function() {
There is absolutely no need to call player.src = "game_character.png"; inside the draw function.
As a general rule, when dealing with animation, try to remove all what you can from the draw function, which should be as fast as possible.
You will need to redraw the canvas each time. Something like this:
function init()
{
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
x = canvas.width / 2; //align to centre of the screen
y = canvas.height / 2; //same as above
speed = 5; //speed for the player to move at
width = 50; //width of the player
height = 50; //height of the player
playerimage = new Image();
playerimage.src = "path/to/image/for/player"; //path to the image to use for the player
canvas.addEventListener("keypress", update);
}
function update(event)
{
if (event.keyCode == 38)
{
y -= speed; //going up
}
if (event.keyCode == 40)
{
y += speed; //going down
}
if (event.keyCode == 37)
{
x -= speed; //going left
}
if (event.keyCode == 39)
{
x += speed; //going right
}
render();
}
function render()
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(playerimage, x, y, width, height);
}
I haven't tested it, so I don't know whether it works and there may be some mistakes here and there. It should work though! If nothing else, it will (hopefully) give you an idea of one way in which you can go about doing it...

Categories

Resources