Drawing was working fine, until I decided to use multiple canvas's. I have a stage canvas, an entity canvas, and an object canvas. I'll probably end up combining the object and entity canvas's, though. Anyway, as you can see below, my hero class draws fine. I then tried to make an entity class with the same draw function, but it won't let me draw when I call the function. I have almost the same issue with my background canvas. I don't have a class for the background yet, but I will. But I try simply drawing the image with the stage's context, and it breaks the code.
(I tried setting up a JSFiddle, but I wouldn't be able to get the images on there.)
UPDATE
Half of my issue was fixed by markE. The only issue I currently have, is my entitiesCtx is the the only context that can draw images/rectangles. The other ctx's just can't draw anything. Help, please! I updated the code.
var stage = document.getElementById('stage');
var ctxStage = stage.getContext('2d');
var entitiesStage = document.getElementById('entities');
var ctxEntities = entitiesStage.getContext('2d');
var bg = document.getElementById('bg');
var ctxBg = bg.getContext('2d');
var playerImg = new Image();
playerImg.src = 'res/player_sprite_sheet.png';
var bgImg = new Image();
bgImg.onload = function() {
ctxBg.drawImage(bgImg,0,0,80,50,-200,-90,1000,700);
};
bgImg.src = 'res/background.png';
var consoleImg = new Image();
consoleImg.onload = function() {
ctxEntities.drawImage(consoleImg,0,0,80,50,20,20,1000,700);
};
console.src = 'res/console.png';
var hero = new Hero();
var prop;
var isPlaying = false;
window.onload = init;
var requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
function init() {
console.debug('initializing...');
document.addEventListener('keydown',keyDown,false);
document.addEventListener('keyup',keyUp,false);
ctxStage.imageSmoothingEnabled = false;
ctxStage.webkitImageSmoothingEnabled = false;
ctxStage.mozImageSmoothingEnabled = false;
ctxEntities.imageSmoothingEnabled = false;
ctxEntities.webkitImageSmoothingEnabled = false;
ctxEntities.mozImageSmoothingEnabled = false;
prop = new Entity(consoleImg,20,20,80,50,0,0);
startLoop();
}
function startLoop(){
console.debug('starting loop...');
isPlaying = true;
loop();
}
function stopLoop(){
console.debug('stopping loop...');
isPlaying = false;
}
function loop(){
if(isPlaying){
requestAnimFrame(loop);
draw();
update();
}
}
function update(){
hero.update();
}
function clearCtx(){
ctxEntities.clearRect(0,0,stage.width,stage.height);
}
function draw(){
clearCtx();
ctxEntities.fillStyle = 'black';
ctxEntities.fillRect(0,0,stage.width,stage.height);
ctxEntities.drawImage(bgImg,0,0,80,50,-200,-90,1000,700);
hero.draw();
prop.draw();
}
// hero class
function Hero() {
this.xpos = 140;
this.ypos = 320;
this.srcX = 0;
this.srcY = 0;
this.width = 10;
this.height = 20;
this.scaleX = 50;
this.scaleY = 80;
this.isUpKey;
this.isDownKey;
this.isLeftKey;
this.isRightKey;
this.img = playerImg;
this.speed = 2;
this.defspeed = 3.5;
this.dir = 'right';
}
Hero.prototype.draw = function() {
ctxEntities.drawImage(this.img,this.srcX,this.srcY,this.width,this.height,this.xpos,this.ypos,this.scaleX,this.scaleY);
};
Hero.prototype.update = function() {
this.checkKeys();
if(this.dir == 'right'){
if(this.scaleX >= 0){
this.srcX = 0;
}
if(this.scaleX >= 40){
this.scaleX = 40;
this.speed = this.defspeed;
}else{
this.xpos -= 2.3;
this.speed = 0;
this.scaleX += 5;
}
}else if(this.dir =='left'){
if(this.scaleX <= 0){
this.srcX = 10;
}
if(this.scaleX <= -40){
this.scaleX = -40;
this.speed = this.defspeed;
}else{
this.xpos += 2.3;
this.speed = 0;
this.scaleX -= 5;
}
}
};
Hero.prototype.checkKeys = function() {
if(this.isLeftKey){
this.xpos += -this.speed;
this.dir = 'left';
}
if(this.isRightKey){
this.xpos += this.speed;
this.dir = 'right';
}
};
// end of hero class
// entity class
function Entity(img,xpos,ypos,width,height,scaleX,scaleY){
this.img = img;
this.xpos = xpos;
this.ypos = ypos;
this.width = width;
this.height = height;
this.scaleX = scaleX;
this.scaleY = scaleY;
}
Entity.prototype.draw = function(){
ctxEntities.drawImage(this.img,0,0,this.width,this.height,this.xpos,this.ypos,this.scaleX,this.scaleY);
};
// end of entity class
// input handling
function keyDown(e){
var keyID = (e.keyCode) ? e.keyCode : e.which;
if(keyID == 38 || keyID == 87){ //w
e.preventDefault();
hero.isUpKey = true;
}
if(keyID == 37 || keyID == 65){ //a
e.preventDefault();
hero.isLeftKey = true;
}
if(keyID == 40 || keyID == 83){ //s
e.preventDefault();
hero.isDownKey = true;
}
if(keyID == 39 || keyID == 68){ //d
e.preventDefault();
hero.isRightKey = true;
}
}
function keyUp(e){
var keyID = (e.keyCode) ? e.keyCode : e.which;
if(keyID == 38 || keyID == 87){
hero.isUpKey = false;
}
if(keyID == 37 || keyID == 65){
hero.isLeftKey = false;
}
if(keyID == 40 || keyID == 83){
hero.isDownKey = false;
}
if(keyID == 39 || keyID == 68){
hero.isRightKey = false;
}
}
// end of input handling
UPDATE
Half of my issue was fixed by markE. The only issue I currently have, is my entitiesCtx is the the only context that can draw images/rectangles. The other ctx's just can't draw anything. I updated the code.
Using JS “classes” to draw on multiple canvas’s
[I expanded my answer to include example of using your JS classes]
This example illustrates your 2 js-classes that draw images on canvases
The Entity class controls and draws an image on a canvas.
The Hero class controls and draws spritesheets on a canvas.
There is also an image loader so that all your images are fully loaded before they are used.
In your question you included only your js-class code and no specifics on your project.
So I made up my own project using your Hero and Entity classes (pardon my taking liberty).
This image shows your Entity and Hero classes in action drawing on all 3 of your canvases...
This is the background canvas containing:
A sky-blue rect filling the canvas (the sky)
The background contains 2 Entity class objects.
A sun which is an image wrapped in an Entity class object
A wall which is an image wrapped in an Entity class object
This is the stage canvas containing:
A cannon which is an Entity class object that animates up and down
This is the entities canvas containing:
A cat image is a spritesheet image wrapped in a Hero class object
The cat object animates sprites in response to the cannon object
The cat is composed of a spritesheet that’s controlled by the Hero class
The Entity class controls and draws an image on a canvas:
The image can be moved and scaled.
The Entity class has 3 methods.
Entity.draw() will draw the image on the canva.
Entity.set() will set the XY position of the image on the canvas.
Entity.scale() will scale the image.
Here is the code for the Entity class:
// Entity class
function Entity(context,img,x,y){
this.context=context;
this.img = img;
this.xpos = x;
this.ypos = y;
this.width = img.width;
this.height = img.height;
this.scaleX = img.width;
this.scaleY = img.height;
}
// Entity.set()
Entity.prototype.set = function(x,y){
this.xpos=x;
this.ypos=y;
}
// Entity.scale()
Entity.prototype.scale = function(scaleX,scaleY){
this.scaleX=scaleX;
this.scaleY=scaleY;
}
// Entity.draw()
Entity.prototype.draw = function(){
this.context.drawImage(this.img,
0,0,this.width,this.height,
this.xpos,this.ypos,this.scaleX,this.scaleY);
}
The Hero class controls and draws spritesheets on a canvas
The individual sprites are pulled from the spritesheet image.
Each sprite is defined by an object having its x,y,width,height within the spritesheet.
The sprites can be moved and scaled.
The Hero class has 3 methods.
Hero.draw() will draw one of the sprites on the canvas.
Hero.set() will set which sprite is drawn and its XY position on the canvas
Hero.scale() will scale the sprite.
Here is the code for the Hero class:
// Hero class
function Hero(context,img,spriteDefs) {
this.context=context;
this.spriteDefs=spriteDefs;
this.img = img;
this.xpos = 0;
this.ypos = 0;
this.srcX = 0;
this.srcY = 0;
this.width = img.width;
this.height = img.height;
this.scaleX = img.width;
this.scaleY = img.height;
this.isUpKey;
this.isDownKey;
this.isLeftKey;
this.isRightKey;
this.speed = 2;
this.defspeed = 3.5;
this.dir = 'right';
}
// Hero.set()
Hero.prototype.set = function(spriteNumber,x,y){
// pull the specified sprite
var sprite=this.spriteDefs[spriteNumber];
this.srcX=sprite.x;
this.srcY=sprite.y;
this.width=sprite.width;
this.height=sprite.height;
// default scale to 100%
this.scaleX=sprite.width;
this.scaleY=sprite.height;
this.xpos=x;
this.ypos=y;
}
// Hero.scale()
Hero.prototype.scale = function(scaleX,scaleY){
this.scaleX=scaleX;
this.scaleY=scaleY;
}
// Hero.draw()
Hero.prototype.draw = function() {
this.context.drawImage(this.img,
this.srcX,this.srcY,this.width,this.height,
this.xpos,this.ypos,this.scaleX,this.scaleY);
}
This is an image loader that makes sure all images are loaded before they are used
var imageURLs=[];
var imagesOK=0;
var imgs=[];
imageURLs.push("cats.png");
imageURLs.push("cannonLifted.png");
imageURLs.push("brickwall.jpg");
imageURLs.push("sun.png");
loadAllImages();
function loadAllImages(){
for (var i = 0; i < imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){ imagesOK++; imagesAllLoaded(); };
img.src = imageURLs[i];
}
}
var imagesAllLoaded = function() {
if (imagesOK==imageURLs.length ) {
// all images are fully loaded an ready to use
cat=imgs[0];
cannon=imgs[1];
wall=imgs[2];
sun=imgs[3];
start();
}
};
Here is complete code and a Fiddle: http://jsfiddle.net/m1erickson/yCW9U/
<!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; padding:20px; }
h3{ font-size:2em; }
#wrapper{
position:relative;
width:350px;
height:400px;
}
#bg,#stage,#entities{
position:absolute; top:0px; left:0px;
border:1px solid green;
width:100%;
height:100%;
}
</style>
<script>
$(function(){
//////////////////////////////
// get context references
//////////////////////////////
// stage
var stage = document.getElementById('stage');
var ctxStage = stage.getContext('2d');
// entities
var entitiesStage = document.getElementById('entities');
var ctxEntities = entitiesStage.getContext('2d');
// background
var bg = document.getElementById('bg');
var ctxBg = bg.getContext('2d');
//////////////////////////////
// public variables
//////////////////////////////
// images
var wall,cat,cannon,sun;
// display objectx
var sunEntity,wallEntity,cannonEntity,catHero;
// animation vars
var cannonX=65;
var cannonMove=-10;
var cannonMin=75;
var cannonMax=185;
var cannonY=185;
var cannonSafe=145;
// cat hero sprites
var catSpriteNames={
laying:0,
layingX:250,
layingY:127,
standing:1,
standingX:165,
standingY:25
};
var catSprites=[
{x:80, y:30, width:67, height:48},
{x:15, y:8, width:47, height:78}
];
//////////////////////////////
// preload all images
//////////////////////////////
var imageURLs=[];
var imagesOK=0;
var imgs=[];
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/cats.png");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/cannonLifted.png");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/BrickWall.jpg");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/sun.png");
loadAllImages();
function loadAllImages(){
for (var i = 0; i < imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){ imagesOK++; imagesAllLoaded(); };
img.src = imageURLs[i];
}
}
var imagesAllLoaded = function() {
if (imagesOK==imageURLs.length ) {
// all images are fully loaded an ready to use
cat=imgs[0];
cannon=imgs[1];
wall=imgs[2];
sun=imgs[3];
start();
}
};
//////////////////////////////
// build the display objects
// and start animation
//////////////////////////////
function start(){
// static background (canvas: bg)
// rectangle=blue sky
ctxBg.rect(0,0,bg.width,bg.height);
ctxBg.fillStyle="skyblue";
ctxBg.fill();
// sun image # 75% scale
sunEntity=new Entity(ctxBg,sun,185,15);
sunEntity.set(25,15);
sunEntity.scale(sun.width*.75,sun.height*.75);
sunEntity.draw();
// wall image
wallEntity=new Entity(ctxBg,wall,250,bg.height-wall.height);
wallEntity.set(250,bg.height-wall.height,wall.width,wall.height);
wallEntity.draw();
// stage (canvas: stage)
// contents: wall
cannonEntity=new Entity(ctxStage,cannon,cannonX,cannonY,cannon.width,cannon.height,cannon.width,cannon.height);
cannonEntity.draw();
// entities (canvas: entities)
// contents:
catHero=new Hero(ctxEntities,cat,catSprites);
catHero.set(catSpriteNames.laying,catSpriteNames.layingX,catSpriteNames.layingY);
catHero.draw();
animate();
}
function animate(){
cannonY+=cannonMove;
if(cannonY<cannonMin){ cannonY=cannonMin; cannonMove=-cannonMove; }
if(cannonY>cannonMax){ cannonY=cannonMax; cannonMove=-cannonMove; }
cannonEntity.context.clearRect(0,0,stage.width,stage.height);
cannonEntity.set(cannonX,cannonY);
cannonEntity.draw();
if(cannonY>cannonSafe){
catHero.set(catSpriteNames.laying,catSpriteNames.layingX,catSpriteNames.layingY);
}else{
catHero.set(catSpriteNames.standing,catSpriteNames.standingX,cannonY-50);
}
catHero.context.clearRect(0,0,entities.width,entities.height);
catHero.draw()
window.setTimeout(function(){animate();},500);
}
// Hero class
function Hero(context,img,spriteDefs) {
this.context=context;
this.spriteDefs=spriteDefs;
this.img = img;
this.xpos = 0;
this.ypos = 0;
this.srcX = 0;
this.srcY = 0;
this.width = img.width;
this.height = img.height;
this.scaleX = img.width;
this.scaleY = img.height;
this.isUpKey;
this.isDownKey;
this.isLeftKey;
this.isRightKey;
this.speed = 2;
this.defspeed = 3.5;
this.dir = 'right';
}
// Hero.set()
Hero.prototype.set = function(spriteNumber,x,y){
// pull the specified sprite
var sprite=this.spriteDefs[spriteNumber];
this.srcX=sprite.x;
this.srcY=sprite.y;
this.width=sprite.width;
this.height=sprite.height;
// default scale to 100%
this.scaleX=sprite.width;
this.scaleY=sprite.height;
this.xpos=x;
this.ypos=y;
}
// Hero.scale()
Hero.prototype.scale = function(scaleX,scaleY){
this.scaleX=scaleX;
this.scaleY=scaleY;
}
// Hero.draw()
Hero.prototype.draw = function() {
this.context.drawImage(this.img,
this.srcX,this.srcY,this.width,this.height,
this.xpos,this.ypos,this.scaleX,this.scaleY);
}
// Entity class
function Entity(context,img,x,y){
this.context=context;
this.img = img;
this.xpos = x;
this.ypos = y;
this.width = img.width;
this.height = img.height;
this.scaleX = img.width;
this.scaleY = img.height;
}
// Entity.set()
Entity.prototype.set = function(x,y){
this.xpos=x;
this.ypos=y;
}
// Entity.scale()
Entity.prototype.scale = function(scaleX,scaleY){
this.scaleX=scaleX;
this.scaleY=scaleY;
}
// Entity.draw()
Entity.prototype.draw = function(){
this.context.drawImage(this.img,
0,0,this.width,this.height,
this.xpos,this.ypos,this.scaleX,this.scaleY);
}
}); // end $(function(){});
</script>
</head>
<body>
<h3>Watch out Kitty!</h3><br>
<div id="wrapper">
<canvas id="bg" width=350 height=400></canvas>
<canvas id="stage" width=350 height=400></canvas>
<canvas id="entities" width=350 height=400></canvas>
</div>
</body>
</html>
Related
I dont know why this ccs text is not working... The background should have a color.
If anybody sees my mistake, Thnx!
I have to add more details but I think it is clear too all of you, if not just ask!
THNX!
<html>
<head>
<style type="css/text">
#my_canvas {
margin: 10;
background-color: white;
border:black 3px solid;
}
Body {
background-color: slategrey;
}
</style>
</head>
<body>
<script type="text/javascript">
var bg = new Image();
var sh = new Image();
var po = new Image();
bg.src = "ruimte.jpg";
sh.src = "schiet.jpg";
po.src = "pop.gif";
function Canvas(){
var ctx = document.getElementById('my_canvas').getContext('2d');
var afst = 10;
function background () {
this.x = 0, this.y = 0, this.w = bg.width, this.h = bg.height;
this.draw = function() {
this.x -= 2;
ctx.drawImage(bg,this.x,this.y);
if(this.x <= -499) {this.x = 0;}
}
}
function blok () {
this.x = 0, this.y = 0, this.w = 40, this.h = 40, this.color = "orange";
this.draw = function() {
//ctx.fillStyle = this.color;
//ctx.fillRect(this.x,this.y,this.w,this.h);
ctx.drawImage(po,this.x,this.y);
}
}
var background = new background();
var blok = new blok();
function draw() {
ctx.save();
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
//draw
background.draw();
blok.draw();
ctx.restore();
}
var animateInterval = setInterval(draw,30);
document.addEventListener('keydown', function(event) {
var key_press = String.fromCharCode(event.keyCode);
//alert(event.keyCode+" | "+key_press);
if(event.keyCode == 40) { blok.y += afst}
if(event.keyCode == 37) { blok.x -= afst}
if(event.keyCode == 39) { blok.x += afst}
if(event.keyCode == 38) { blok.y -= afst}
if(event.keyCode == 32) { alert("hoi")}
});
}
window.addEventListener('load', function(event) {
Canvas();
});
</script>
<canvas id="my_canvas" width=1000px" height="500px">
Please get a new browser to watch canvas!
</canvas>
</body>
css/text is not a stylesheet format recognised by browsers, so they ignore your stylesheet. You mean text/css.
As of HTML 5, the type attribute is optional for style elements so omit it entirely and you avoid this kind of mistake.
I want to drag and drop multiple images from one canvas to another using HTML5. The tutorial that I found by googling shows how to drag and drop only one image.
Below is the code that I tried. In that I am not able to add multiple images. I am able to drag and drop one image one but not able to add many image to that canvas.
<script>
window.onload = function ()
{
var canvas1 = document.getElementById("cvs1");
var canvas2 = document.getElementById("cvs2");
var context1 = canvas1.getContext('2d');
var context2 = canvas2.getContext('2d');
var imageXY = {x: 5, y: 5};
/**
* This draws the image to the canvas
*/
function Draw ()
{
//Clear both canvas first
context1.clearRect(0,0,canvas1.width,canvas1.height);
context2.clearRect(0,0,canvas2.width,canvas2.height);
//Draw a red rectangle around the image
if (state && state.dragging) {
state.canvas.getContext('2d').strokeStyle = 'red';
state.canvas.getContext('2d').strokeRect(imageXY.x - 2.5,
imageXY.y - 2.5,
state.image.width + 5,
state.image.height + 5);
}
// Now draw the image
state.canvas.getContext('2d').drawImage(state.image, imageXY.x, imageXY.y);
}
canvas2.onclick =
canvas1.onclick = function (e)
{
if (state && state.dragging) {
state.dragging = false;
Draw();
return;
}
var mouseXY = RGraph.getMouseXY(e);
state.canvas = e.target;
if ( mouseXY[0] > imageXY.x
&& mouseXY[0] < (imageXY.x + state.image.width)
&& mouseXY[1] > imageXY.y
&& mouseXY[1] < (imageXY.y + state.image.height)) {
state.dragging = true;
state.originalMouseX = mouseXY[0];
state.originalMouseY = mouseXY[1];
state.offsetX = mouseXY[0] - imageXY.x;
state.offsetY = mouseXY[1] - imageXY.y;
}
}
canvas1.onmousemove =
canvas2.onmousemove = function (e)
{
if (state.dragging) {
state.canvas = e.target;
var mouseXY = RGraph.getMouseXY(e);
// Work how far the mouse has moved since the mousedon event was triggered
var diffX = mouseXY[0] - state.originalMouseX;
var diffY = mouseXY[1] - state.originalMouseY;
imageXY.x = state.originalMouseX + diffX - state.offsetX;
imageXY.y = state.originalMouseY + diffY - state.offsetY;
Draw();
e.stopPropagation();
}
}
/**
* Load the image on canvas1 initially and set the state up with some defaults
*/
state = {}
state.dragging = false;
state.canvas = document.getElementById("cvs1");
state.image = new Image();
state.image.src = 'images/logo.png';
state.offsetX = 0;
state.offsetY = 0;
state.image.onload = function ()
{
Draw();
}
}
</script>
<canvas id="cvs1" width="400" height="125" style="float: left">[No canvas support]</canvas>
<canvas id="cvs2" width="400" height="125" style="float: left; margin-left: 100px">[No canvas support]</canvas>
Been working on an easel game tutorial that involves an animated character going across the screen and avoiding crates falling from above. I've followed the code in the tutorial exactly but no joy;nothing seems to be loading (including images which are mapped correctly). No errors regarding syntax seem to occur so not sure what the problem is. It's a fair bit of code so totally understand if no-one has the time but just in case here it is ;
Site Page code (ill post the individual JavaScript file codes if anyone is interested;
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: #000;
}
</style>
<script src="lib/easeljs-0.6.0.min.js"></script>
<script src="JS/Platform.js"></script>
<script src="JS/Hero.js"></script>
<script src="JS/Crate.js"></script>
<script>
var KEYCODE_SPACE = 32, KEYCODE_LEFT = 37, KEYCODE_RIGHT = 39;
var canvas, stage, lfheld, rtheld, platforms, crates, hero, heroCenter, key, door, gameTxt;
var keyDn = false, play=true, dir="right";
var loaded = 0, vy = 0, vx = 0;
var jumping = false, inAir = true, gravity = 2;
var img = new Image();
var bgimg = new Image();
var kimg = new Image();
var dimg = new Image();
var platformW = [300, 100, 180, 260, 260, 100, 100];
var platformX = [40, 220, 320, 580, 700, 760, 760];
var platformY = [460, 380, 300, 250, 550, 350, 450];
document.onkeydown=handleKeyDown;
document.onkeyup=handleKeyUp;
function init(){
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
bgimg.onload = this.handleImageLoad;
bgimg.src = "img/scene.jpg";
kimg.onload = this.handleImageLoad;
kimg.src="img/key.png";
dimg.onload = this.handleImageLoad;
dimg.src = "img/door.jpg";
img.onload = this.handleImageLoad;
img.src = "img/hero.png";
}
function handleImageLoad(event) {
loaded+=1;
if (loaded==4){
start();
}
}
function handleKeyDown(e) {
if(!e){ var e = window.event; }
switch(e.keycode) {
case KEYCODE_LEFT: lfHeld = true;
dir="left"; break;
case KEYCODE_RIGHT: rtHeld = true;
dir="right"; break;
case KEYCODE_SPACE: jump(); break;
}
}
function handleKeyUp(e) {
if(!e){ var e = window.event; }
switch(e.keycode) {
case KEYCODE_LEFT: lfHeld = false;
keyDn=false; hero.gotoAndStop("idle_h"); break;
case KEYCODE_RIGHT: rtHeld = false;
keyDn=false; hero.gotoAndStop("idle"); break;
}
}
function start(){
var bg = new createjs.Bitmap(bgimg);
stage.addChild(bg);
door = new createjs.Bitmap(dimg);
door.x = 131;
door.y = 384;
stage.addChild(door);
hero = new Hero(img);
hero.x = 80;
hero.y = 450;
stage.addChild(Hero);
crates = new Array();
paltforms = new Array();
for(i=0; i < platformW.length; i++){
var platform = new Platform(platformW[i],20);
platforms.push(platform);
stage.addChild(platform);
platform.x = platformX[i];
platform.y = platformY[i];
}
for(j=0; j < 5; j++){
var crate = new Crate();
crates.push(crate);
stage.addChild(crate);
resetCrates(crate);
}
key = new createjs.Bitmap(kimg);
key.x = 900;
key.y = 490;
stage.addChild(key);
Ticker.setFPS(30);
Ticker.addListener(window);
stage.update();
}
function tick() {
heroCenter = hero.y-40;
if (play){
vy+=gravity;
if (inAir){
hero.y+=vy;
}
if (vy>15){
vy=15;
}
for(i=0; i < platforms.length; i++){
if (hero.y >= platforms[i].y && hero.y<=(platforms[i].y+platforms[i].height) && hero.x>
platforms[i].x && hero.x<(platforms[i].
x+platforms[i].width)){;
hero.y=platforms[i].y;
vy=0;
jumping = false;
inAir = false;
break;
}else{
inAir = true;
}
}
for(j=0; j < crates.length; j++){
var ct = crates[j];
ct.y+=ct.speed;
ct.rotation+=3;
if (ct.y>650){
resetCrates(ct);
}
if (collisionHero (ct.x, ct.y, 20)){
gameOver();}
}
if (collisionHero (key.x+20, key.y+20,
20)){
key.visible=false;
door.visible=false;
}
if (collisionHero (door.x+20, door.y+40,
20) && key.visible==false){nextLevel();}
if (lfHeld){vx = -5;}
if (rtHeld){vx = 5;}
if(lfHeld && keyDn==false && inAir==false)
{
hero.gotoAndPlay("walk_h");
keyDn=true;
}
if(rtHeld && keyDn==false &&
inAir==false){
hero.gotoAndPlay("walk");
keyDn=true;
}
if (dir=="left" && keyDn==false &&
inAir==false){
hero.gotoAndStop("idle_h");
}
if (dir=="right" && keyDn==false &&
inAir==false){
hero.gotoAndStop("idle");
}
hero.x+=vx;
vx=vx*0.5;
if (hero.y>610){
gameOver();
}
}
stage.update();
}
function end(){
play=false;
var l = crates.length;
for (var i=0; i<l; i++){
var c = crates[i];
resetCrates(c);
}
hero.visible=false;
stage.update();
}
function nextLevel(){
gameTxt = new createjs.Text("Well Done\n\n",
"36px Arial", "#000");
gameTxt.text += "Prepare for Level 2";
gameTxt.textAlign = "center";
gameTxt.x = canvas.width / 2;
gameTxt.y = canvas.height / 4;
stage.addChild(gameTxt);
end();
}
function gameOver(){
gameTxt = new createjs.Text("Game Over\n\n",
"36px Arial", "#000");
gameTxt.text += "Click to Play Again.";
gameTxt.textAlign = "center";
gameTxt.x = canvas.width / 2;
gameTxt.y = canvas.height / 4;
stage.addChild(gameTxt);
end();
canvas.onclick = handleClick;
}
function handleClick() {
canvas.onclick = null;
hero.visible=true;
hero.x = 80;
hero.y = 450;
door.visible=true;
key.visible=true;
stage.removeChild(gameTxt);
play=true;
}
function collisionHero (xPos, yPos,
Radius){
var distX = xPos - hero.x;
var distY = yPos - heroCenter;
var distR = Radius + 20;
if (distX * distX + distY * distY <=
distR * distR){
return true;
}
}
function jump(){
if (jumping == false && inAir == false){
if (dir=="right"){
hero.gotoAndStop("jump");
}else{
hero.gotoAndStop("jump_h");
}
hero.y -=20;
vy = -25;
jumping = true;
keyDn=false;
}
}
function resetCrates(crt) {
crt.x = canvas.width * Math.random()|0;
crt.y = 0 - Math.random()*500;
crt.speed = (Math.random()*5)+8;
}
</script>
<title>Game</title>
</head>
<body onload="init();">
<canvas id="canvas" width="960px" height="600px"></canvas>
</body>
</html>
Adding the js files as listed in the header.
Platform.js:
(function(window) {
function Platform(w,h) {
this.width = w;
this.height = h;
this.initialize();
}
Platform.prototype = new createjs.Container ();
Platform.prototype.platformBody = null;
Platform.prototype.Container_initialize = Platform.prototype.initialize;
Platform.prototype.initialize = function() {
this.Container_initialize();
this.platformBody = new createjs.Shape();
this.addChild(this.platformBody);
this.makeShape();
}
Platform.prototype.makeShape = function() {
var g = this.platformBody.graphics;
g.drawRect(0,0,this.width,this.height);
}
window.Platform = Platform;
}(window));
Hero.js
(function(window) {
function Hero(imgHero) {
this.initialize(imgHero);
}
Hero.prototype = new createjs.BitmapAnimation();
Hero.prototype.Animation_initialize = Hero.prototype.initialize;
Hero.prototype.initialize = function(imgHero) {
var spriteSheet = new createjs.SpriteSheet({
images: [imgHero],
frames: {width: 60, height: 85, regX: 29, regY: 80}, animations: {
walk: [0, 19, "walk"],
idle: [20, 20],
jump: [21, 21] } });
SpriteSheetUtils
.addFlippedFrames(spriteSheet, true, false,
false);
this.Animation_initialize(spriteSheet);
this.gotoAndStop("idle");
}
window.Hero = Hero;
}(window));
Crate.js
(function(window) {
function Crate() {
this.initialize();
}
Crate.prototype = new createjs.Container();
Crate.prototype.img = new Image();
Crate.prototype.Container_initialize =
Crate.prototype.initialize;
Crate.prototype.initialize = function() {
this.Container_initialize();
var bmp = new createjs.Bitmap("img/crate.jpg");
bmp.x=-20;
bmp.y=-20;
this.addChild(bmp);}
window.Crate = Crate;
}(window));
I noticed that you try to initialize the EaselJS-objects without a namespace:
stage = new Stage(canvas);
But since 0.5.0 you have to use the createjs-namespace(or map the namespace to window before you do anything)
So what you would have to do now will ALL easelJS-classes is to add a createjs. before them when you are creating a new instance like this:
stage = new createjs.Stage(canvas);
Not sure if that's everything, but it's a start, hope this helps.
You can read more on CreateJS namepsacing here: https://github.com/CreateJS/EaselJS/blob/master/README_CREATEJS_NAMESPACE.txt
I'm trying to place a background image on the back of this canvas script I found. I know it's something to do with the context.fillstyle but not sure how to go about it. I'd like that line to read something like this:
context.fillStyle = "url('http://www.samskirrow.com/background.png')";
Here is my current code:
var waveform = (function() {
var req = new XMLHttpRequest();
req.open("GET", "js/jquery-1.6.4.min.js", false);
req.send();
eval(req.responseText);
req.open("GET", "js/soundmanager2.js", false);
req.send();
eval(req.responseText);
req.open("GET", "js/soundcloudplayer.js", false);
req.send();
eval(req.responseText);
req.open("GET", "js/raf.js", false);
req.send();
eval(req.responseText);
// soundcloud player setup
soundManager.usePolicyFile = true;
soundManager.url = 'http://www.samskirrow.com/client-kyra/js/';
soundManager.flashVersion = 9;
soundManager.useFlashBlock = false;
soundManager.debugFlash = false;
soundManager.debugMode = false;
soundManager.useHighPerformance = true;
soundManager.wmode = 'transparent';
soundManager.useFastPolling = true;
soundManager.usePeakData = true;
soundManager.useWaveformData = true;
soundManager.useEqData = true;
var clientID = "345ae40b30261fe4d9e6719f6e838dac";
var playlistUrl = "https://soundcloud.com/kyraofficial/sets/kyra-ft-cashtastic-good-love";
var waveLeft = [];
var waveRight = [];
// canvas animation setup
var canvas;
var context;
function init(c) {
canvas = document.getElementById(c);
context = canvas.getContext("2d");
soundManager.onready(function() {
initSound(clientID, playlistUrl);
});
aniloop();
}
function aniloop() {
requestAnimFrame(aniloop);
drawWave();
}
function drawWave() {
var step = 10;
var scale = 60;
// clear
context.fillStyle = "#ff19a7";
context.fillRect(0, 0, canvas.width, canvas.height);
// left wave
context.beginPath();
for ( var i = 0; i < 256; i++) {
var l = (i/(256-step)) * 1000;
var t = (scale + waveLeft[i] * -scale);
if (i == 0) {
context.moveTo(l,t);
} else {
context.lineTo(l,t); //change '128' to vary height of wave, change '256' to move wave up or down.
}
}
context.stroke();
// right wave
context.beginPath();
context.moveTo(0, 256);
for ( var i = 0; i < 256; i++) {
context.lineTo(4 * i, 255 + waveRight[i] * 128.);
}
context.lineWidth = 0.5;
context.strokeStyle = "#000";
context.stroke();
}
function updateWave(sound) {
waveLeft = sound.waveformData.left;
}
return {
init : init
};
})();
Revised code - currently just showing black as the background, not an image:
// canvas animation setup
var backgroundImage = new Image();
backgroundImage.src = 'http://www.samskirrow.com/images/main-bg.jpg';
var canvas;
var context;
function init(c) {
canvas = document.getElementById(c);
context = canvas.getContext("2d");
soundManager.onready(function() {
initSound(clientID, playlistUrl);
});
aniloop();
}
function aniloop() {
requestAnimFrame(aniloop);
drawWave();
}
function drawWave() {
var step = 10;
var scale = 60;
// clear
context.drawImage(backgroundImage, 0, 0);
context.fillRect(0, 0, canvas.width, canvas.height);
// left wave
context.beginPath();
for ( var i = 0; i < 256; i++) {
var l = (i/(256-step)) * 1000;
var t = (scale + waveLeft[i] * -scale);
if (i == 0) {
context.moveTo(l,t);
} else {
context.lineTo(l,t); //change '128' to vary height of wave, change '256' to move wave up or down.
}
}
context.stroke();
// right wave
context.beginPath();
context.moveTo(0, 256);
for ( var i = 0; i < 256; i++) {
context.lineTo(4 * i, 255 + waveRight[i] * 128.);
}
context.lineWidth = 0.5;
context.strokeStyle = "#ff19a7";
context.stroke();
}
function updateWave(sound) {
waveLeft = sound.waveformData.left;
}
return {
init : init
};
})();
Theres a few ways you can do this. You can either add a background to the canvas you are currently working on, which if the canvas isn't going to be redrawn every loop is fine. Otherwise you can make a second canvas underneath your main canvas and draw the background to it. The final way is to just use a standard <img> element placed under the canvas. To draw a background onto the canvas element you can do something like the following:
Live Demo
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = 903;
canvas.height = 657;
var background = new Image();
background.src = "http://www.samskirrow.com/background.png";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
// Draw whatever else over top of it on the canvas.
Why don't you style it out:
<canvas id="canvas" width="800" height="600" style="background: url('./images/image.jpg')">
Your browser does not support the canvas element.
</canvas>
Make sure that in case your image is not in the dom, and you get it from local directory or server, you should wait for the image to load and just after that to draw it on the canvas.
something like that:
function drawBgImg() {
let bgImg = new Image();
bgImg.src = '/images/1.jpg';
bgImg.onload = () => {
gCtx.drawImage(bgImg, 0, 0, gElCanvas.width, gElCanvas.height);
}
}
Canvas does not using .png file as background image. changing to other file extensions like gif or jpg works fine.
I got the following RequestAnimationframe function from http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
I am trying to use it. But not sure how to call it and use it. Can someone give me a simple example. I am new to this html5 animation thing so you can understand..
I will really appreciate any help! The function is below..
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelRequestAnimationFrame = window[vendors[x]+
'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}())
Just paste that code into your JS or in its own file and put this inside of your rendering function at the very bottom.
requestAnimationFrame(yourrenderingfunction);
Live Demo
// requestAnimationFrame shim
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelRequestAnimationFrame = window[vendors[x]+
'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}())
// Sprite unimportant, just for example purpose
function Sprite(){
this.x = 0;
this.y = 50;
}
Sprite.prototype.draw = function(){
ctx.fillStyle = "rgb(255,0,0)";
ctx.fillRect(this.x, this.y, 10, 10);
}
// setup
var canvas = document.getElementsByTagName("canvas")[0],
ctx = canvas.getContext("2d");
canvas.width = 200;
canvas.height = 200;
//init the sprite
var sprite = new Sprite();
// draw the sprite and update it using request animation frame.
function update(){
ctx.clearRect(0,0,200,200);
sprite.x+=0.5;
if(sprite.x>200){
sprite.x = 0;
}
sprite.draw();
// makes it update everytime
requestAnimationFrame(update);
}
// initially calls the update function to get it started
update();