Im making a car parking project with Adobe Animate CC (HTML5).
I have into my canvas a Car and its Wheels.With the command below i can rotate the wheels left or right by pressing keyboard arrows.
document.onkeydown = keyHandler.bind(this);
function keyHandler(event) {
var e = event||window.event;
//left
if(e.keyCode == 37) {
this.car.wheels3.rotation-=2;
But i want to make it to rotate in a certain rotation ratio , like a real wheel of a car rotates.I think i have to make a method but i dont know how to use rotate property with the method i want to create.Any thought/ help appreciated.
You need wheel animation actually:
createjs.Tween.get(car.wheel,{loop:true,override:true}).to({rotation:"360"}, 1000);
//or
createjs.Tween.get(car.wheel,{loop:true,override:true}).to({rotation:"-360"}, 1000);
Update, based on new circumstances:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<script>
function init()
{
var stage = new createjs.Stage("canvas");
createjs.Ticker.setFPS(24); //set some FPS
createjs.Ticker.addEventListener("tick", stage); //set autiomatic refresh
//let's draw something like wheels, with registration point somewhere in the middle :)
var wheels=new createjs.Shape();
wheels.graphics.beginFill("#CCCCCC").drawRect(-100,0,20,50);
wheels.graphics.beginFill("#CCCCCC").drawRect(-100,15,200,20);
wheels.graphics.beginFill("#CCCCCC").drawRect(100,0,20,50);
stage.addChild(wheels);
wheels.x=200;
wheels.y=100;
document.addEventListener("keydown", onKeyDown );
var wheelsInitialRotation=wheels.rotation; //save whells initial rotation
var maximumAngleForRotation=20; //set maximum angle
function onKeyDown(e)
{
var amount;
e = e || window.event;
switch(e.keyCode)
{
//right
case 39:
amount=2;
break;
//left
case 37:
amount=-2;
break;
//all other
default:
amount=0;
}
//check is new angle is not more or less then allowed :)
if(!(wheels.rotation+amount>wheelsInitialRotation+maximumAngleForRotation || wheels.rotation+amount<wheelsInitialRotation-maximumAngleForRotation))
{
wheels.rotation+=amount;
}
}
}
</script>
</head>
<body onload="init();">
<canvas id="canvas" width="400" height="400"></canvas>
</body>
</html>
Related
I am trying to create a rect that moves on keypress for a pong game and when I press the key the left rect disappears..
Any ideas how to fix the problem? It is really important..
The code is written in vanilla javascript so please don't write jQuery..
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pong</title>
<script type="text/javascript">
var x = 100;
var y = 100;
var xmoveFirst = 720;
var ymoveFirst = 0;
var xmoveSecond = 30 ;
var ymoveSecond = 0;
function canvas() {
var can = document.getElementById('theCanvas');
can.style.backgroundColor = "black";
var ctx = can.getContext('2d');
//first player
ctx.fillStyle="white";
ctx.fillRect(xmoveFirst,ymoveFirst,5,75);
//second player
ctx.fillStyle = 'white';
ctx.fillRect(xmoveSecond,ymoveSecond,5,75);
//first player move
function moveFirst(eFirst) {
ctx.clearRect(0,0,750,750); //clear rects
if (eFirst.keyCode == 40) {
ymoveFirst+=25;
console.log("first,"+ymoveFirst);
}
else if (eFirst.keyCode == 38) {
ymoveFirst-=25;
console.log("first,"+ymoveFirst);
}
ctx.fillStyle="white";
ctx.fillRect(xmoveFirst,ymoveFirst,5,75);
ctx.fillRect(xmoveSecond,ymoveSecond,5,75);
}
var first = document.onkeydown = moveFirst;
//second player move
function moveSecond(eSecond) {
ctx.clearRect(0,0,750,750);
if (eSecond.keyCode == 83) {
ymoveSecond+=25;
console.log("second,"+ymoveSecond);
}
else if (eSecond.keyCode == 87) {
ymoveSecond-=25;
}
ctx.fillStyle="white";
ctx.fillRect(xmoveFirst,ymoveFirst,5,75);
ctx.fillRect(xmoveSecond,ymoveSecond,5,75);
console.log("second,"+ymoveSecond)
}
var second = document.onkeydown = moveSecond;
}
83,87
</script>
</head>
<body onload="canvas()">
<canvas id="theCanvas" width="750" height="750"></canvas>
</body>
</html>
This line: can.width=can.width; resets the canvas width.
When you change the canvas size (width or height), you clear the canvas (making everything black). After this line, you are only redrawing the rightmost paddle, so the left one remains missing.
You'll need to redraw the leftmost paddle as well if you want it to come back. Here is the modified moveRight() function:
function moveRight(eFirst) {
if (eFirst.keyCode==40) {
ymoveFirst+=25;
console.log(ymoveFirst);
}
else if (eFirst.keyCode==38) {
ymoveFirst-=25;
console.log(ymoveFirst);
}
can.width=can.width;
ctx.fillStyle="white";
// Redraw BOTH paddles
ctx.fillRect(xmoveFirst,ymoveFirst,5,75);
ctx.fillRect(xmoveSecond,ymoveSecond,5,75);
}
Also, replace
document.onkeydown = moveFirst; and document.onkeydown = moveSecond;
with
document.addEventListener("keydown", moveFirst);, and document.addEventListener("keydown", moveSecond);
Currently, you are overwritting the first listener with document.onkeydown = moveSecond;. By using addEventListener, you don't overwrite the ones that already exist.
I'm fairly new to Javascript and using a canvas in general and I cant get collision detection to work with my canvas walls.
I normally have a small square painted on the canvas that I can control with the arrow keys on the keyboard but it would continue past the canvas.
This is the working code without my attempts of collision detection.
<!DOCTYPE html>
<html>
<head>
<canvas id = "gameCanvas" width="400" height="400" style = "border:1px solid #000000;"></canvas>
<style type="text/css"></style>
</head>
<body>
<script type="text/javascript">
var c = document.getElementById("gameCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "rgb(255, 0, 0)";
var snake = {
x: 5
, y: 5
};
function drawSnake() {
ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height);
ctx.fillRect(snake.x ,snake.y,20,20);
}
window.addEventListener("keydown", function(event) {
if (event.keyCode == 39)
snake.x += 5;
else if (event.keyCode == 37)
snake.x -= 5;
else if (event.keyCode == 38)
snake.y -= 5;
else if (event.keyCode == 40)
snake.y += 5;
drawSnake();
});
drawSnake();
</script>
</body>
</html>
This is my attempt at collision detection.
//Wall Collision
if(snake.x >= canvas.w || snake.x <= -1 || snake.y >= canvas.h || snake.y <= -1) {
return;
}
Entering this code leaves me with a blank canvas and I don't understand why.
I want the square to reset its position once it collides with the canvas wall and that's where I'm having all the trouble.
You shouldn't put it under addEventListener. Then, the return is ending the JS script.
You want to put your collision detection code in (the beginning of) drawSnake().
See this working example.
There are also a few other things wrong with your code that I feel that I should address (all changed in the example).
<canvas> should be in the <body> element, not the <head>
canvas is not defined in JS (you can remove it from ctx.canvas.width
change canvas.w and canvas.h to ctx.width and ctx.height in the collision detection code
instead of returning from the drawSnake() function, reset the snake to its default coordinates
draw a better snake
I am having trouble creating game on html canvas. The premise of the game is you have to catch the balloons before they hit the ground. I am having problems with the background of the canvas and the basket is not moving with the mouse.
The background should be black and the basket should be following the mouse curser.
https://jsfiddle.net/pgkL09j7/8/
<html>
<head>
<title>Sean Coyne</title>
<link rel="stylesheet" type="text/css" href="home.css">
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body onload="start_game()">
<body>
<section>
<article>
<div id="logo"><img src="LogoComic.png" id="Logo"></div><br></br>
<div id="canvas">
<canvas id="c" style="border:5px solid orange" height="500" width="500"></canvas>
<p id="p1"></p>
<script>
var balloon_x=100;
var balloon_y=0;
var basket_x=100;
var basket_y=100;
var points=0;
//Background colour of canvas
var c = document.getElementById("c");
var ctx = c.getContext("2d");
ctx.fillStyle = "#000";
ctx.fillRect(0,0,500,500);
//Here is the event listener
mycanv.addEventListener("mousemove",seenmotion, false);
function seenmotion(e) {
//This is the code for the mouse
//moving over the canvas.
var bounding_box=c.getBoundingClientRect();
basket_x=(e.clientX-bounding_box.left) *
(c.width/bounding_box.width);
basket_y=(e.clientY-bounding_box.top) *
(c.height/bounding_box.height);
}
function start_game() {
setInterval(game_loop, 50);
}
function game_loop() {
// The code above is called every 50ms and is a
// frame-redraw-game-animation loop.
c.width = c.width;
// Below is the code that draws the objects
draw_balloon(balloon_x,balloon_y);
draw_basket(basket_x,basket_y);
// Below is the code that updates the balloons location
balloon_x++;
if (balloon_x>c.width) {
balloon_x=0;
}
//Here is the collision detection code
if (collision(balloon_x, balloon_y, basket_x, basket_y)) {
points -= 0.5;
}
//Here is the code for the point system
points+=1;
// and let's stick it in the top right.
var integerpoints=Math.floor(points); // make it into an integer
ctx.font="bold 24px sans-serif ";
ctx.fillText(integerpoints, c.width-50, 50);
}
context.clearRect ( 0 , 0 , 500, 500 );
function collision(basket_x, basket_y, ball_x, ball_y) {
if(balloon_y + 85 < basket_y) {
return false;
}
if (balloon_y > basket_y + 91) {
return false;
}
if (balloon_x + 80 < basket_x) {
return false;
}
if (balloon_x > basket_x + 80) {
return false;
}
return true;
}
// Code to stop the game when we're finished playing
function stop_game() {
}
//Code for the ball
function draw_balloon(x,y) {
var balloon_img=new Image();
balloon_img.src="balloon.png";
ctx.drawImage(balloon_img,x,y);
}
//Code for the basket
function draw_basket(x,y) {
var basket_img=new Image();
basket_img.src="basket.png";
ctx.drawImage(basket_img,x,y);
}
</script>
</div>
</article>
</section>
</body>
</html>
You have to change the variable for the mouselistener. So instead of
mycanv.addEventListener("mousemove",seenmotion, false);
you have to write this
c.addEventListener("mousemove",seenmotion, false);
This move the basket with the mouse, but the image isn't still right. You have to subtract half of width and height of the image from the x and y coordinate.
To fix your background you have to modify your CSS. the article and the section tag have both full width/height und an own background. This shouldn't be to hard to fix, just change the background of #c to black.
#c {
background-color: black;
}
Here's the jsfiddle: https://jsfiddle.net/pgkL09j7/10/
Visit http://www.w3schools.com/ for more information about CSS and JS. Also the code can be more easier and structured.
I want to use onmouseover in this javascript code. So, whenever I move the mouse over the square, the function changeColor executes and picks one color each time, from the two given colors.
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<body>
<h1>Canvas Art Gallary</h1>
<canvas id="myCanvas" width="400" height="300" style="border:10px solid #c3c3c3">
</canvas>
<script type="text/javascript">
function changeColor(){
ctx.fillStyle = "#FFFFFF";
ctx.fillStyle = "#04B45F";
}
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(150,100,100,100);
</script>
</body>
</html>
Thanks
Listen for mouse events and toggle the color on our own custom mouseenter
Note: the rect does not have mouseenter so we must custom build one.
Listen for mousemove events
On rect mouseenter: set a wasInside flag to true and changeColor() which toggles the rect color
On rect mouseleave: clear a wasInside flag to indicate the mouse has left the rect.
Example code and a Demo: http://jsfiddle.net/m1erickson/9GcbH/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color:ivory; }
#canvas{border:1px solid red;background-color:black;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
var toggle=0;
var x=150;
var y=100;
var w=100;
var h=100;
var wasInside=false;
// draw the rect to start
ctx.fillStyle = "red";
ctx.fillRect(x,y,w,h);
function changeColor(){
if(toggle==0){
ctx.fillStyle = "#FFFFFF";
toggle=1;
}else{
ctx.fillStyle = "#04B45F";
toggle=0;
}
ctx.fillRect(x,y,w,h);
}
function handleMouseMove(e){
e.preventDefault();
var mx=parseInt(e.clientX-offsetX);
var my=parseInt(e.clientY-offsetY);
var isInsideNow=(mx>x && mx<x+w && my>y && my<=y+h);
if(isInsideNow && !wasInside){
changeColor();
wasInside=true;
}else if(!isInsideNow && wasInside){
wasInside=false;
}
}
$("#canvas").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});
</script>
</head>
<body>
<h4>Rect color toggles white-green<br>each time mouse moves over it.</h4>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
[ Addition: explain steps of toggling ]
Each time the mouse enters the rect changeColor is called.
changeColor both changes the color and also changes toggle.
Here's a step-by-step:
1. toggle==0 at the beginning of the ap
2. mouse enters rect and changeColor is called.
3. changeColor changes color to #ffffff because toggle==0.
4. changeColor changes toggle=1
5. mouse exits rect
6. mouse enters rect again and changeColor is called again.
7. changeColor changes color to #04b45f because toggle==1.
8. changeColor changes toggle=0;
mouseover will only know when you're over the canvas, so you need to detect you're above the square (I'm using the variables already defined by you):
var sqx1 = c.offsetLeft + 150; //left top corner of the square respect to the window
var sqy1 = c.offsetTop + 100;
var sqx2 = sqx1 + 100; //right bottom corner of the square respect to the window
var sqy2 = sqy1 + 100;
var lastOverSquare = false;
c.addEventListener('mousemove', function(e) {
var overSquare =
(sqx1 <= e.pageX && sqx2 >= e.pageX) &&
(sqy1 <= e.pageY && sqy2 >= e.pageY);
if (overSquare && !lastOverSquare) changeColour(); //change only when it enters the square, not every move when we're already over it.
lastOverSquare = overSquare;
}, false);
var colours = ['#FFFFFF', '#04B45F'];
var currentColour = 0;
ctx.fillStyle = colours[currentColour];
function changeColour() {
currentColour = (currentColour + 1) % colours.length;
ctx.fillStyle = colours[currentColour];
}
I'm trying to develop game similar to snake games in old model phones. I created the game, which you can have a look at here. But when controlling the snake I switched the width and height of the snake to turn in any direction, but I want to make the snake to look like real snake, I mean it should have an L shape when turning and gradually changes into straight again, Please give me any idea, how I can do that using canvas. the snake is a fillrect() in canvas.
The following is the entire code..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Snake</title>
</head>
<body>
Use Arrow keys of to control the snake.
<canvas id="can_game" height="400" width="400" style="border:1px solid;"></canvas>
<div id="score_div"></div>
<div id="time">0.00</div>
<script type="text/javascript">
var score=0,fps=30,canvas=document.getElementById("can_game"),context=canvas.getContext('2d'),dir="",score_div=document.getElementById("score_div"),width_h=45,pass='left',timediv=document.getElementById("time"),time=0.00;
var player = {
color : '#ff00',
px :'180',
py : '384',
height : '12',
width : '45',
draw : function(){
context.fillRect(this.px,this.py,this.width,this.height);
}
}
var ball = {
x :Math.round(Math.random(4)*400),
y : Math.round(Math.random(4)*400),
draw : function() {
context.beginPath();
context.fillStyle = "#ff0000";
context.arc(this.x,this.y,6,0,2*Math.PI,false);
context.fill();
}
}
setInterval(function(){
score_div.innerHTML=score;
timediv.innerHTML=Math.round(time/1000)+" Seconds";
time=parseInt(time)+1000/fps;
update();
draw();
var test=hitTestPoint(player.px,player.py,player.width,player.height,ball.x,ball.y);
if(test===true)
{
ball.x=Math.round(Math.random(80)*400);
ball.y=Math.round(Math.random(80)*400);
score+=10;
width_h+=3;
}
console.log(player.py,canvas.width);
if(player.px <=0)
player.px=360;
else if(player.px >= (canvas.width))
player.px=0;
else if(player.py <= 0)
player.py=360;
else if(player.py >= (canvas.height))
player.py=0;
document.onkeydown = function() {
var key_pressed = window.event.keyCode;
/* if(key_pressed == 32)
dir = "freeze";*/
if(key_pressed == 37)
dir = "left";
else if(key_pressed == 39)
dir = "right";
else if(key_pressed == 38)
dir = "up";
else if(key_pressed == 40)
dir = "down";
};
},1000/fps);
function hitTestPoint(x1, y1, w1, h1, x2, y2)
{
if ((x1 <= x2 && x1+w1 >= x2) &&
(y1 <= y2 && y1+h1 >= y2))
return true;
else
return false;
}
function draw()
{
context.clearRect(0,0,canvas.width,canvas.height);
player.draw();
ball.draw();
context.fill();
}
function update()
{
switch(dir){
case "left":
player.px-=3;
player.width=width_h;
player.height=12;
break;
case "right":
player.px= parseInt(player.px)+3;
player.width=width_h;
player.height=12;
break;
case "up":
player.py-=3;
player.width=12;
player.height=width_h;
break;
case "down":
player.py+=3;
player.width=12;
player.height=width_h;
break;
}
}
</script>
</body>
</html>
You might want to take a look at this CSS deck tutorial to solve your problem.
Here the trick is , that the snake is composed of individual small and discrete blocks rather than the one as in your case where its a static block, and every time the snake is progressed one step, one block is popped from the rear and a new block is added to the top(face).
So when the snakes moves in another direction(or axis) its face block are gradually added in another axis and it gives an illusion of snake turning in the way you expect it