Two virtual joystick not coming - javascript

I am trying to make two joysticks on the single page with the help of code provided below but only one joystick appear.I am putting one - one joystick in different jumbotron , to differentiate. I tried even with different div id's but still it is not working. Also second jumbotron joystick is coming up in this example.
Can some help ??
Code :
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>
<script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="js/underscore-min.js"></script>
<script type="text/javascript" src="js/backbone-min.js"></script>
<script type="text/javascript" src="js/joystick_view.js"></script>
</head>
<body>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-3">Fluid jumbotron</h1>
<p class="lead">This is a modified jumbotron that occupies the entire horizontal space of its parent.</p>
<script type="text/html" id="joystick-view">
<canvas id="joystickCanvas" width="<%= squareSize %>" height="<%= squareSize %>" style="width: <%= squareSize %>px; height: <%= squareSize %>px;">
</canvas>
</script>
<div id="joystickContent">
</div>
<div>
firstx: <span id="xVal"></span><br/>
y: <span id="yVal"></span><br/>
</div>
<script type="text/javascript">
$(document).ready(function(){
var joystickView = new JoystickView(150, function(callbackView){
$("#joystickContent").append(callbackView.render().el);
setTimeout(function(){
callbackView.renderSprite();
}, 0);
});
joystickView.bind("verticalMove", function(y){
$("#yVal").html(y);
});
joystickView.bind("horizontalMove", function(x){
$("#xVal").html(x);
});
});
</script>
</div>
</div>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-3">Fluid jumbotron</h1>
<p class="lead">This is a modified jumbotron that occupies the entire horizontal space of its parent.</p>
<script type="text/html" id="joystick-view">
<canvas id="joystickCanvas" width="<%= squareSize %>" height="<%= squareSize %>" style="width: <%= squareSize %>px; height: <%= squareSize %>px;">
</canvas>
</script>
<div id="joystickContent">
</div>
<div>
x: <span id="xVal"></span><br/>
y: <span id="yVal"></span><br/>
</div>
<script type="text/javascript">
$(document).ready(function(){
var joystickView1 = new JoystickView(150, function(callbackView){
$("#joystickContent").append(callbackView.render().el);
setTimeout(function(){
callbackView.renderSprite();
}, 0);
});
joystickView.bind("verticalMove", function(y){
$("#yVal").html(y);
});
joystickView.bind("horizontalMove", function(x){
$("#xVal").html(x);
});
});
</script>
</div>
</div>
</body>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js'></script>
</html>
plus this the javascript code working:
var INACTIVE = 0;
var ACTIVE = 1;
var SECONDS_INACTIVE = 0.5;
function loadSprite(src, callback) {
var sprite = new Image();
sprite.onload = callback;
sprite.src = src;
return sprite;
}
JoystickView = Backbone.View.extend({
events: {
"touchstart": "startControl",
"touchmove": "move",
"touchend": "endCotrol",
"mousedown": "startControl",
"mouseup": "endControl",
"mousemove": "move"
},
initialize: function(squareSize, finishedLoadCallback){
this.squareSize = squareSize;
this.template = _.template($("#joystick-view").html());
this.state = INACTIVE;
this.x = 0;
this.y = 0;
this.canvas = null;
this.context = null;
this.radius = (this.squareSize / 2) * 0.5;
this.finishedLoadCallback = finishedLoadCallback;
this.joyStickLoaded = false;
this.backgroundLoaded = false;
this.lastTouch = new Date().getTime();
self = this;
setTimeout(function(){
self._retractJoystickForInactivity();
}, 1000);
this.sprite = loadSprite("img/button.png", function(){
self.joyStickLoaded = true;
self._tryCallback();
});
this.background = loadSprite("img/canvas.png", function(){
self.backgroundLoaded = true;
self._tryCallback();
});
},
_retractJoystickForInactivity: function(){
var framesPerSec = 15;
var self = this;
setTimeout(function(){
var currentTime = new Date().getTime();
if(currentTime - self.lastTouch >= SECONDS_INACTIVE * 1000){
self._retractToMiddle();
self.renderSprite();
}
self._retractJoystickForInactivity();
}, parseInt(1000 / framesPerSec, 10));
},
_tryCallback: function(){
if(this.backgroundLoaded && this.joyStickLoaded){
var self = this;
this.finishedLoadCallback(self);
}
},
startControl: function(evt){
this.state = ACTIVE;
},
endControl: function(evt){
this.state = INACTIVE;
this.x = 0;
this.y = 0;
this.renderSprite();
},
move: function(evt){
if(this.state == INACTIVE){
return;
}
this.lastTouch = new Date().getTime();
var x, y;
if(evt.originalEvent && evt.originalEvent.touches){
evt.preventDefault();
var left = 0;
var fromTop = 0;
elem = $(this.canvas)[0];
while(elem) {
left = left + parseInt(elem.offsetLeft);
fromTop = fromTop + parseInt(elem.offsetTop);
elem = elem.offsetParent;
}
x = evt.originalEvent.touches[0].clientX - left;
y = evt.originalEvent.touches[0].clientY - fromTop;
} else {
x = evt.offsetX;
y = evt.offsetY;
}
this._mutateToCartesian(x, y);
this._triggerChange();
},
_triggerChange: function(){
var xPercent = this.x / this.radius;
var yPercent = this.y / this.radius;
if(Math.abs(xPercent) > 1.0){
xPercent /= Math.abs(xPercent);
}
if(Math.abs(yPercent) > 1.0){
yPercent /= Math.abs(yPercent);
}
this.trigger("horizontalMove", xPercent);
this.trigger("verticalMove", yPercent);
},
_mutateToCartesian: function(x, y){
x -= (this.squareSize) / 2;
y *= -1;
y += (this.squareSize) / 2;
if(isNaN(y)){
y = this.squareSize / 2;
}
this.x = x;
this.y = y;
if(this._valuesExceedRadius(this.x, this.y)){
this._traceNewValues();
}
this.renderSprite();
},
_retractToMiddle: function(){
var percentLoss = 0.1;
var toKeep = 1.0 - percentLoss;
var xSign = 1;
var ySign = 1;
if(this.x != 0){
xSign = this.x / Math.abs(this.x);
}
if(this.y != 0) {
ySign = this.y / Math.abs(this.y);
}
this.x = Math.floor(toKeep * Math.abs(this.x)) * xSign;
this.y = Math.floor(toKeep * Math.abs(this.y)) * ySign;
},
_traceNewValues: function(){
var slope = this.y / this.x;
var xIncr = 1;
if(this.x < 0){
xIncr = -1;
}
for(var x=0; x<this.squareSize / 2; x+=xIncr){
var y = x * slope;
if(this._valuesExceedRadius(x, y)){
break;
}
}
this.x = x;
this.y = y;
},
_cartesianToCanvas: function(x, y){
var newX = x + this.squareSize / 2;
var newY = y - (this.squareSize / 2);
newY = newY * -1;
return {
x: newX,
y: newY
}
},
_valuesExceedRadius: function(x, y){
if(x === 0){
return y > this.radius;
}
return Math.pow(x, 2) + Math.pow(y, 2) > Math.pow(this.radius, 2);
},
renderSprite: function(){
var originalWidth = 89;
var originalHeight = 89;
var spriteWidth = 50;
var spriteHeight = 50;
var pixelsLeft = 0; //ofset for sprite on img
var pixelsTop = 0; //offset for sprite on img
var coords = this._cartesianToCanvas(this.x, this.y);
if(this.context == null){
return;
}
// hack dunno why I need the 2x
this.context.clearRect(0, 0, this.squareSize * 2, this.squareSize);
var backImageSize = 300;
this.context.drawImage(this.background,
0,
0,
backImageSize,
backImageSize,
0,
0,
this.squareSize,
this.squareSize
)
this.context.drawImage(this.sprite,
pixelsLeft,
pixelsTop,
originalWidth,
originalHeight,
coords.x - spriteWidth / 2,
coords.y - spriteHeight / 2,
spriteWidth,
spriteHeight
);
},
render: function(){
var renderData = {
squareSize: this.squareSize
};
this.$el.html(this.template(renderData));
this.canvas = this.$('#joystickCanvas')[0];
this.context = this.canvas.getContext('2d');
this.renderSprite();
return this;
}
});
This is the image of whats happening

Related

javascript - multiple moving walls

I am making a game like flappy bird , the only difference is that the bird moves by using the mouse pointer location any where on the canvas. So for the obstacle i made walls but the walls are appearing in a bunch. I am not able to make walls that appear on regular interval in the canvas .
Required image :-
i am getting this :-
var context;
var screenWidth;
var screenHeight;
var ball;
var wall = [];
var gameStatus;
var mouseX;
var mouseY;
var running = false;
var raf;
gameIntialize();
gameDraw();
function Ball() {
this.radius = 16;
this.x = 25;
this.y = screenHeight / 2;
this.ballDraw = function() {
context.beginPath();
context.arc(this.x, this.y, 16, 0, 2 * Math.PI);
context.fillStyle = 'green';
context.fill();
}
};
function Wall() {
this.thickness = 10;
this.wallPositionY = screenHeight;
this.wallPositionX = screenWidth;
this.spacing = 0;
if (this.wallPositionY > 400 && this.wallPositionY <= 500) {
this.spacing = Math.floor(Math.random() * (100 - 50) + 50);
} else if (this.wallPositionY > 500) {
this.spacing = Math.floor(Math.random() * (200 - 100) + 100);
} else {
this.spacing = 45;
}
this.heightFromTheTop = Math.floor(Math.random() * (this.wallPositionY / 6 - 3 / 4 * this.wallPositionY) + this.wallPositionY);
this.heightFromTheBottom = this.wallPositionY - (this.heightFromTheTop + this.spacing);
this.speed = 6;
this.draw = function() {
context.fillStyle = 'yellow';
context.fillRect(this.wallPositionX, 0, this.thickness, this.heightFromTheTop);
context.fillRect(this.wallPositionX, this.wallPositionY - this.heightFromTheBottom, this.thickness, this.heightFromTheBottom);
}
this.update = function() {
this.wallPositionX = this.wallPositionX - this.speed;
}
this.offscreen = function() {
if (this.wallPositionX < -this.thickness) {
return true;
} else {
return false;
}
}
this.newWall = function() {
if (this.wallPositionX < screenWidth / 2) {
return true;
} else {
return false;
}
}
};
function gameIntialize() {
var canvass = document.getElementById('canvas');
context = canvas.getContext('2d');
screenWidth = window.innerWidth;
screenHeight = window.innerHeight;
canvas.width = screenWidth;
canvas.height = screenHeight;
ball = new Ball();
wall.push(new Wall());
// window.addEventListener('resize', resizeScreen, false);
canvas.addEventListener('mousemove', function(e) {
if (!running) {
ball.x = e.clientX;
ball.y = e.clientY;
}
});
}
function gameDraw() {
context.fillStyle = "#aaaaaa";
context.fillRect(0, 0, screenWidth, screenHeight);
ball.ballDraw();
for (var i = wall.length - 1; i >= 0; i--) {
wall[i].draw();
wall[i].update();
if (wall[i].offscreen()) {
wall.splice(i, 1);
}
var test_interval = setInterval(function() {
wall.push(new Wall());
}, 5000);
}
raf = window.requestAnimationFrame(gameDraw);
}
body {
margin: 0px
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>game-run</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script src="game.js"></script>
</html>
What is wrong with this code? I appreciate any help!
Your setInterval creation code is sitting inside your game loop.
That means you're creating a new 5 second interval for EVERY FRAME!
Take it out of there and things should be fine.
Modified snippet:
var context;
var screenWidth;
var screenHeight;
var ball;
var wall = [];
var gameStatus;
var mouseX;
var mouseY;
var running = false;
var raf;
gameIntialize();
gameDraw();
function Ball() {
this.radius = 16;
this.x = 25;
this.y = screenHeight / 2;
this.ballDraw = function() {
context.beginPath();
context.arc(this.x, this.y, 16, 0, 2 * Math.PI);
context.fillStyle = 'green';
context.fill();
}
};
function Wall() {
this.thickness = 10;
this.wallPositionY = screenHeight;
this.wallPositionX = screenWidth;
this.spacing = 0;
if (this.wallPositionY > 400 && this.wallPositionY <= 500) {
this.spacing = Math.floor(Math.random() * (100 - 50) + 50);
} else if (this.wallPositionY > 500) {
this.spacing = Math.floor(Math.random() * (200 - 100) + 100);
} else {
this.spacing = 45;
}
this.heightFromTheTop = Math.floor(Math.random() * (this.wallPositionY / 6 - 3 / 4 * this.wallPositionY) + this.wallPositionY);
this.heightFromTheBottom = this.wallPositionY - (this.heightFromTheTop + this.spacing);
this.speed = 6;
this.draw = function() {
context.fillStyle = 'yellow';
context.fillRect(this.wallPositionX, 0, this.thickness, this.heightFromTheTop);
context.fillRect(this.wallPositionX, this.wallPositionY - this.heightFromTheBottom, this.thickness, this.heightFromTheBottom);
}
this.update = function() {
this.wallPositionX = this.wallPositionX - this.speed;
}
this.offscreen = function() {
if (this.wallPositionX < -this.thickness) {
return true;
} else {
return false;
}
}
this.newWall = function() {
if (this.wallPositionX < screenWidth / 2) {
return true;
} else {
return false;
}
}
};
function gameIntialize() {
var canvass = document.getElementById('canvas');
context = canvas.getContext('2d');
screenWidth = window.innerWidth;
screenHeight = window.innerHeight;
canvas.width = screenWidth;
canvas.height = screenHeight;
ball = new Ball();
wall.push(new Wall());
// window.addEventListener('resize', resizeScreen, false);
canvas.addEventListener('mousemove', function(e) {
if (!running) {
ball.x = e.clientX;
ball.y = e.clientY;
}
});
}
function gameDraw() {
context.fillStyle = "#aaaaaa";
context.fillRect(0, 0, screenWidth, screenHeight);
ball.ballDraw();
for (var i = wall.length - 1; i >= 0; i--) {
wall[i].draw();
wall[i].update();
if (wall[i].offscreen()) {
wall.splice(i, 1);
}
}
raf = window.requestAnimationFrame(gameDraw);
}
var test_interval = setInterval(function() {
wall.push(new Wall());
}, 1500);
body {
margin: 0px
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>game-run</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script src="game.js"></script>
</html>

How to move character in two speeds without one affecting the other?

OK, so this is a little hard to explain. I'm making a canvas-based point-and-click 2d game. You can look around (move the environment) by dragging the mouse horizontally across the screen. And move the character by clicking where you want him to go. Kinda like This War of Mine. Here's a simplified version of what I got...
MOUSE ACTIONS:
var held, mouseX, mouseXInitial;
window.addEventListener('mousedown',function(e){
held = true;
mouseXInitial = mouseX;
});
window.addEventListener('mouseup',function(e){
held = false;
});
window.addEventListener('mousemove',function(e){
mouseX = e.clientX;
});
mouseEvents();
LOOKING AROUND (dragging across the screen to look around the environment):
var sharedParentObject = {
scrolledAmount: null,
scrolling: function(){
if (held){
this.scrolledAmount = mouseX - mouseXInitial;
this.x = this.xInitial + this.scrolledAmount;
}
},
inputShared: function(){
var that = this;
window.addEventListener('mousedown',function(e){
that.xInitial = that.x;
});
window.addEventListener('mousemove',function(e){
that.scrolling();
});
}
}
MOVING THE CHARACTER:
function Character(){
this.speed = 2;
this.target = null;
this.input = function(){
var that = this;
window.addEventListener('mouseup',function(e){
that.target = that.mouseXInitial;
that.target += that.scrolledAmount;
});
}
this.update = function(){
if (this.target){
//moving right
if (this.x + this.w/2 < this.target){
this.x += this.speed;
}
//moving left
if (this.x + this.w/2 > this.target){
this.x -= this.speed;
}
}
}
}
Character.prototype = Object.create(sharedParentObject);
This works but the problem is that once I start dragging across the screen to look around, while the character is already walking, it gets all weird and jittery. I understand why this is happening. The character's x is getting changed in both the character class and the parent class at the same time. Is there a way to have it so the character can keep walking towards the target, while still getting moved as I scroll the environment? Kinda doing both, without one affecting the other..
All you need to do is track the distance the mouse have moved between the onmousedown and onmouseup events. If the distance is very small, then the user has clicked on one spot, if the distance is larger then they are trying to pan the scene.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
display: block;
margin-top: 20px;
margin-left: auto;
margin-right: auto;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
// ES5 Friendly class functions
// (Supports overloading & single inheritance)
var _class = (function() {
"use strict";
/*
All a class is in JS is a function that
acts as a constructor and an object (prototype)
that holds the properties shared across all
instances (static vars, constants & functions).
*/
function _class(constructor,prototype) {
prototype.base = null;
prototype.super = constructor;
constructor.prototype = prototype;
return constructor;
}
_class.extends = function(base,constructor,prototype) {
for (var property in base.prototype) {
if (!prototype[property]) {
prototype[property] = base.prototype[property];
}
}
function bundledConstructor() {
base.apply(this,arguments);
constructor.apply(this,arguments);
}
prototype.base = base;
prototype.super = bundledConstructor;
bundledConstructor.prototype = prototype;
return bundledConstructor;
}
return _class;
})();
void function() {
"use strict";
// Classes
// Encapsulate canvas element
var Viewport = _class(
function(canvasID,width,height,bgColour) {
this.canvas = document.getElementById(canvasID) || null;
this.width = width || 1.0;
this.height = height || 1.0;
this.bgColour = bgColour || "gray";
this.hWidth = this.width >> 1;
this.hHeight = this.height >> 1;
this.canvas.width = this.width;
this.canvas.height = this.height;
this.ctx = this.canvas.getContext("2d");
this.ctx.translate(this.hWidth,this.hHeight);
var bounds = this.canvas.getBoundingClientRect();
this.leftMargin = bounds.left;
this.topMargin = bounds.top;
},{
clear: function() {
var ctx = this.ctx;
ctx.fillStyle = this.bgColour;
ctx.fillRect(-this.hWidth,-this.hHeight,this.width,this.height);
}
}
);
// This is a class used to encapsulate
// the scene's panning/zooming.
var Camera = _class(
// Constructor Function
function(viewport,x,y) {
this.viewport = viewport || null;
this.x = x || 0.0;
this.y = y || 0.0;
this.scale = 1.0;
this.invScale = 1.0 / this.scale;
this.allowUserInput = false;
this.mouseDown = false;
this.mouseLastX = 0.0;
this.mouseLastY = 0.0;
viewport.canvas.addEventListener("wheel",this.onwheel.bind(this));
viewport.canvas.addEventListener("mousedown",this.onmousedown.bind(this));
viewport.canvas.addEventListener("mouseup",this.onmouseup.bind(this));
viewport.canvas.addEventListener("mousemove",this.onmousemove.bind(this));
},
// Prototype (constant values & functions go here)
{
scaleCoordinates: function(x,y) {
return [
(x - this.viewport.hWidth) * this.invScale + this.x,
(y - this.viewport.hHeight) * this.invScale + this.y
];
},
scaleDimensions: function(width,height) {
return [
width * this.invScale,
height * this.invScale
];
},
pan: function(deltaX,deltaY) {
this.x += deltaX;
this.y += deltaY;
},
zoom: function(deltaScale) {
this.scale += deltaScale;
this.scale = Math.max(0.0,this.scale);
this.invScale = 1.0 / this.scale;
},
onwheel: function(e) {
if (this.allowUserInput) {
var deltaY = -Math.sign(e.deltaY) * (e.deltaY / e.deltaY) * 0.25;
this.zoom(deltaY);
}
},
onmousedown: function(e) {
this.mouseDown = true;
[
this.mouseLastX,
this.mouseLastY
] = this.scaleCoordinates(
e.clientX - this.viewport.leftMargin,
e.clientY - this.viewport.topMargin
);
},
onmouseup: function(e) {
this.mouseDown = false;
},
onmousemove: function(e) {
if (this.allowUserInput && this.mouseDown) {
var [
mouseX,
mouseY
] = this.scaleCoordinates(
e.clientX - this.viewport.leftMargin,
e.clientY - this.viewport.topMargin
);
this.pan(
this.mouseLastX - mouseX,
this.mouseLastY - mouseY
);
}
}
}
);
// Contains basic behaviour all game objects will have
var GameObject = _class(
function(x,y,width,height,colour) {
this.x = x || 0.0;
this.y = y || 0.0;
this.width = width || 1.0;
this.height = height || 1.0;
this.colour = colour || "darkblue";
this.dx = 0.0;
this.dy = 0.0;
this._draw_x = 0.0;
this._draw_y = 0.0;
this._draw_width = 0.0;
this._draw_height = 0.0;
},{
updateDrawParameters: function(camera) {
this._draw_width = this.width * camera.scale;
this._draw_height = this.height * camera.scale;
this._draw_x = ((this.x - camera.x) * camera.scale) - this._draw_width * 0.5;
this._draw_y = ((this.y - camera.y) * camera.scale) - this._draw_height * 0.5;
},
tick: function() {
},
render: function(viewport) {
var ctx = viewport.ctx;
ctx.fillStyle = this.colour;
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.rect(this._draw_x,this._draw_y,this._draw_width,this._draw_height);
ctx.fill();
ctx.stroke();
}
}
);
// A more specialized type of game object that
// can move to a specific location
var MoveAgent = _class.extends(GameObject,
function(x,y,width,height,colour) {
this.currentState = this.STATE_IDLE;
this.targetX = 0.0;
this.targetY = 0.0;
},{
STATE_IDLE: 1000,
STATE_MOVING_TO_TARGET: 1001,
MOVE_SPEED: 1.0,
GOAL_TOLERANCE: 5.0, // How close is 'good enough' to the target
moveTo: function(x,y) {
this.targetX = x || 0.0;
this.targetY = y || 0.0;
this.currentState = this.STATE_MOVING_TO_TARGET;
},
tick: function() {
switch(this.currentState) {
case this.STATE_IDLE:
break;
case this.STATE_MOVING_TO_TARGET:
var x = this.targetX - this.x;
var y = this.targetY - this.y;
var l = x * x + y * y;
if (l < this.GOAL_TOLERANCE * this.GOAL_TOLERANCE) {
this.currentState = this.STATE_IDLE;
} else {
l = 1.0 / Math.sqrt(l);
this.dx = x * l * this.MOVE_SPEED;
this.dy = y * l * this.MOVE_SPEED;
this.x += this.dx;
this.y += this.dy;
}
break;
}
}
}
);
var ControlledMoveAgent = _class.extends(MoveAgent,
function(x,y,width,height,colour,camera) {
this.camera = camera || null;
this.mouseDown = false;
this.mouseX = 0.0;
this.mouseY = 0.0;
viewport.canvas.addEventListener("mousedown",this.onmousedown.bind(this));
viewport.canvas.addEventListener("mouseup",this.onmouseup.bind(this));
viewport.canvas.addEventListener("mousemove",this.onmousemove.bind(this));
},{
MOVE_TOLLERANCE: 5.0,
onmousedown: function(e) {
if (e.button === 0) {
this.mouseDown = true;
this.mouseX = e.clientX;
this.mouseY = e.clientY;
}
},
onmouseup: function(e) {
if (e.button === 0 && this.mouseDown) {
this.mouseDown = false;
var x = e.clientX - this.camera.viewport.leftMargin;
var y = e.clientY - this.camera.viewport.topMargin;
[x,y] = this.camera.scaleCoordinates(x,y);
this.moveTo(x,y);
}
},
onmousemove: function(e) {
if (this.mouseDown) {
var x = this.mouseX - e.clientX;
var y = this.mouseY - e.clientY;
var l = Math.sqrt(x * x + y * y);
if (l > this.MOVE_TOLLERANCE) {
this.mouseDown = false;
}
}
}
}
);
// Vars
var camera = null;
var viewport = null;
var scenery = [];
var character = null;
// Functions
function loop() {
// Tick
for (var i = 0; i < scenery.length; ++i) {
scenery[i].updateDrawParameters(camera);
}
character.tick();
character.updateDrawParameters(camera);
// Render
viewport.clear();
for (var i = 0; i < scenery.length; ++i) {
scenery[i].render(viewport);
}
character.render(viewport);
//
requestAnimationFrame(loop);
}
// Entry Point
onload = function() {
viewport = new Viewport("canvas",180,160,"gray");
camera = new Camera(viewport,0,0);
camera.allowUserInput = true;
camera.zoom(0.25);
for (var i = 0; i < 10; ++i) {
scenery[i] = new GameObject(
180 * Math.random() - 90,
160 * Math.random() - 80,
10 + Math.random() * 10,
10 + Math.random() * 10,
"#" + ((Math.random() * 255) | 0).toString(16)
+ ((Math.random() * 255) | 0).toString(16)
+ ((Math.random() * 255) | 0).toString(16)
);
}
character = new ControlledMoveAgent(0,0,10,10,"darkred",camera);
loop();
}
}()
</script>
</body>
</html>

Moving an Object according to mouse coordinates

How do I get the following script to work? I wanted to be able to move the ship to the mouse coordinates. The space itself should move and the ship should stay in the centerview.
Would be great if you can modify the script as everybody writes his functions different.
Finally if the button is clicked I want the ship to move to that destination
I tried it when it worked and the ship never moved and I don't know if it has to do with the prototype.update function or not.
Is prototype.update or .render the same as if I would write this.update or this.render?
<script>
function domanDown(evt)
{
switch (evt)
{
case 38: /* Up arrow was pressed or button pressed*/
offsetY+=100 ;
break;
case 40: /* Down arrow was pressed or button pressed*/
offsetY-=100;
break;
case 37: /* Left arrow was pressedor button pressed*/
offsetX+=100;
break;
case 39: /* Right arrow was pressed or button pressed*/
offsetX-=100;
break;
}
}
window.requestAnimationFrame = function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(f) {
window.setTimeout(f,1e3/60);
}
}();
var Obj = function (x,y,sp,size){
this.size = size;
this.x = x;
this.y = y;
this.color = sp;
this.selected = 0;
}
var Planet_Class = function (x,y,sp){
this.type = 'Planet_Class';
this.depot = 11;
this.xtype = new Obj(x,y,sp,10);
w.objects.push(this);
Planet_Class.prototype.update =function () {
}
Planet_Class.prototype.render =function () {
ctx.save();
ctx.beginPath();
ctx.fillStyle = this.xtype.color;
ctx.fillRect(this.xtype.x, this.xtype.y,this.xtype.size,this.xtype.size);
ctx.fill();
ctx.restore();
}
}
var Usership = function(x,y,sp){
this.depot = 10;
this.type = 'Usership';
this.xtype = new Obj(x,y,sp,10);
w.objects.push(this);
Usership.prototype.update =function (x,y) {
this.xtype.x = x || 20;
this.xtype.y = y || 20;
}
Usership.prototype.render =function () {
ctx.save();
ctx.beginPath();
ctx.fillStyle = this.xtype.color;
ctx.fillRect(this.xtype.x, this.xtype.y,this.xtype.size,this.xtype.size);
ctx.fill();
ctx.restore();
}
}
var World = function(){
this.objects = new Array();
this.count = function(type,sp){
var cnt = 0;
for(var k = 0;k<this.objects.length;k++)
cnt++;
return cnt;
}
}
renderWorld = function(){
requestAnimationFrame(renderWorld);
var spliceArray = Array();
ctx.beginPath();
objcnt = w.objects.length;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "white";
ctx.fill();
i = 0;
while(i < objcnt){
w.objects[i].update();
w.objects[i].render();
if(w.objects[i].depot < 1)
spliceArray.push(i);
i++;
}
for(var k = 0;k<spliceArray.length;k++)
{
w.objects.splice(spliceArray[k],1); }
}
function r1(max,min){
return (Math.floor(Math.random() * (max - min)) + 1);
}
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d"),
width = 1024,
height = 768;
offsetX = (canvas.width/2)-300; /Startpoint x for the Ship
offsetY = (canvas.height/2)-300; /Startpoint y for the Ship
generateshipx = -offsetX + (canvas.width/2);
generateshipy = -offsetY + (canvas.height/2);
mX = generateshipx;
mY = generateshipy;
w = new World();
new Usership(generateshipx,generateshipy,'green');
for(i=1;i<4;i++){
new Planet_Class(r1(600,2),r1(600,2),'red');
}
canvas.addEventListener("click", function (e) {
mX = e.pageX- canvas.offsetLeft -offsetX) ;
mY = e.pageY - canvas.offsetTop -offsetY) ;
});
renderWorld();
</script>
<html>
<head>
</head>
<body style="background-color:black;">
<canvas style="z-index:1" width="1024" height="768" id="canvas"></canvas>
<input type="button" style="z-index:2; position:absolute; top:300; left:10" value="uo" onCLick="domanDown(38)()">
<input type="button" style="z-index:2; position:absolute; top:340; left:10" value="down" onCLick="domanDown(40)">
<input type="button" style="z-index:2; position:absolute; top:380; left:10" value="left" onCLick="domanDown(37)">
<input type="button" style="z-index:2; position:absolute; top:420; left:10" value="right" onCLick="domanDown(39)">
<input type="button" style="z-index:2; position:absolute; top:460; left:10" value="move" onCLick="moveObj()">
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
cursor: crosshair;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var bounds = null;
var isRotating = false;
var isMoving = false;
var pan = {
x: 0.0,
y: 0.0
};
var target = {
x: 0.0,
y: 0.0,
dist: 0.0
};
var ship = {
x: (canvasWidth * 0.5)|0,
y: (canvasHeight * 0.5)|0,
width: 10.0,
height: 10.0,
rotation: 0.0,
deltaRotation: 0.0
};
var stars = [];
stars.length = 100;
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
bounds = canvas.getBoundingClientRect();
for (var i = 0; i < stars.length; ++i) {
stars[i] = {
x: (Math.random() * 4 * canvasWidth - 2 * canvasWidth)|0,
y: (Math.random() * 4 * canvasHeight - 2 * canvasHeight)|0
};
}
loop();
}
window.onmousedown = function(e) {
isRotating = true;
isMoving = false;
target.x = pan.x + e.clientX - bounds.left;
target.y = pan.y + e.clientY - bounds.top;
}
function loop() {
// Tick
// Rotate to face target
if (isRotating) {
// Vector creation
var tX = ship.x - target.x;
var tY = ship.y - target.y;
var tL = Math.sqrt(tX**2 + tY**2);
var fX = Math.sin(ship.rotation);
var fY = -Math.cos(ship.rotation);
var sX = Math.sin(ship.rotation + Math.PI * 0.5);
var sY = -Math.cos(ship.rotation + Math.PI * 0.5);
// Normalization
tX = tX / tL;
tY = tY / tL;
// Left or right?
var a = 1.0 - Math.abs(tX * fX + tY * fY);
ship.rotation += 0.075 * (sX * tX + sY * tY < 0.0 ? 1.0 : -1.0);
if (a < 0.01) {
target.dist = tL;
isRotating = false;
isMoving = true;
}
}
// Accelerate to target
if (isMoving) {
ship.x += Math.sin(ship.rotation) * 1.0;
ship.y -= Math.cos(ship.rotation) * 1.0;
if (--target.dist < 0.0) {
isMoving = false;
}
}
// Render
// Update pan coordinates
pan.x = ship.x - canvasWidth * 0.5;
pan.y = ship.y - canvasHeight * 0.5;
// Draw background
ctx.fillStyle = "#222222";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
ctx.fillStyle = "white";
for (var i = 0; i < stars.length; ++i) {
ctx.fillRect(
stars[i].x - pan.x,
stars[i].y - pan.y,
2,
2
);
}
// Draw ship
ctx.strokeStyle = "white";
ctx.fillStyle = "darkred";
ctx.translate(canvasWidth * 0.5,canvasHeight * 0.5);
ctx.rotate(ship.rotation);
ctx.beginPath();
ctx.moveTo(-ship.width * 0.5,ship.height * 0.5);
ctx.lineTo(ship.width * 0.5,ship.height * 0.5);
ctx.lineTo(0.0,-ship.height * 0.5);
ctx.lineTo(-ship.width * 0.5,ship.height * 0.5);
ctx.fill();
ctx.stroke();
ctx.rotate(-ship.rotation);
ctx.translate(-canvasWidth * 0.5,-canvasHeight * 0.5);
requestAnimationFrame(loop);
}
</script>
</body>
</html>

OCR using HTML5 canvas

I'm a complete newbee to HTML5 and Javascript. I'm trying to make this simple app in HTML5 where a user can draw any alphabet on the canvas and the alphabet gets recognized using ocrad.js. However, upon executing this script, no matter what alphabet i draw, the output is always the alphabet 'I'. My guess is that an empty canvas is being passed as an argument to OCRAD or there is an error in linking ocrad.js .
I'm not even sure, how to include the ocrad API as 'src' as i'm completely new to Javascript. Here's what i have written so far.
<canvas id="myCanvas" width="275" height="400" onmouseup="release()" onmousedown="lc=1" onmousemove="Draw(event)" onclick="putPoint(event)" style="border:1px solid #000000;">
</canvas>
<div id="buttons">
<input type="button" id="clear" value="Clear">
</div>
<div id="buttons">
<input type="button" id="recognize" value="Recognize">
</div>
<script src="ocrad.js/ocrad.js"></script>
<script type="text/javascript">
var cnv = document.getElementById('myCanvas')
var ctx = cnv.getContext('2d')
var lc=0
var prX=-1
var prY=-1
var dot= ctx.createImageData(2,2)
for (i=0; i<dot.data.length; i+=4){
dot.data[i+0]=0
dot.data[i+1]=160
dot.data[i+2]=230
dot.data[i+3]=255
}
document.getElementById('clear').addEventListener('click', function() {
ctx.clearRect(0, 0, cnv.width, cnv.height);
}, false);
function release(){
lc=0
prX=-1
}
function putPoint(event){
var bb, x, y
bb = cnv.getBoundingClientRect()
x = (event.clientX-bb.left) * (cnv.width/bb.width)
y = (event.clientY-bb.top) * (cnv.height/bb.height)
ctx.putImageData(dot,x,y)
}
function Draw(event){
if(lc==1){
var bb, x, y
bb = cnv.getBoundingClientRect()
x = (event.clientX-bb.left) * (cnv.width/bb.width)
y = (event.clientY-bb.top) * (cnv.height/bb.height)
if (prX!=-1){
ctx.beginPath()
ctx.moveTo(prX,prY)
ctx.lineTo(x,y)
ctx.lineWidth=10
ctx.closePath()
ctx.strokeStyle='rgb(0,0,0)'
ctx.stroke()
}
prX=x
prY=y
}
}
document.getElementById('recognize').addEventListener('click', function() {
var string = OCRAD(cnv)
alert(string)
});
</script>
Any help in fixing this is appreciated. Thank You.
There is some strange bug in your code or in library, here is another working example, that should help:
var c = document.getElementById('c'),
o = c.getContext('2d');
function reset_canvas() {
o.fillStyle = 'white'
o.fillRect(0, 0, c.width, c.height)
o.fillStyle = 'black'
}
var drag = false,
lastX, lastY;
c.onmousedown = function(e) {
drag = true;
lastX = 0;
lastY = 0;
e.preventDefault();
c.onmousemove(e)
}
c.onmouseup = function(e) {
drag = false;
e.preventDefault();
runOCR()
}
c.onmousemove = function(e) {
e.preventDefault()
var rect = c.getBoundingClientRect();
var r = 5;
function dot(x, y) {
o.beginPath()
o.moveTo(x + r, y)
o.arc(x, y, r, 0, Math.PI * 2)
o.fill()
}
if (drag) {
var x = e.clientX - rect.left,
y = e.clientY - rect.top;
if (lastX && lastY) {
var dx = x - lastX,
dy = y - lastY;
var d = Math.sqrt(dx * dx + dy * dy);
for (var i = 1; i < d; i += 2) {
dot(lastX + dx / d * i, lastY + dy / d * i)
}
}
dot(x, y)
lastX = x;
lastY = y;
}
}
document.body.ondragover = function() {
document.body.className = 'dragging';
return false
}
document.body.ondragend = function() {
document.body.className = '';
return false
}
document.body.onclick = function() {
document.body.className = '';
}
document.body.ondrop = function(e) {
e.preventDefault();
document.body.className = '';
picked_file(e.dataTransfer.files[0]);
return false;
}
function open_picker() {
var e = document.createEvent("MouseEvents");
e.initEvent('click', true, true);
document.getElementById('picker').dispatchEvent(e);
}
function runOCR(image_data, raw_feed) {
var response = OCRAD(c);
if ('innerText' in document.getElementById("text")) {
document.getElementById("text").innerText = response;
} else {
document.getElementById("text").textContent = response;
}
}
reset_canvas()
<script src="http://antimatter15.com/ocrad.js/ocrad.js"></script>
<div id="demo">
<canvas style="border:1px solid grey;" id='c' class="" width="300" height="150"></canvas>
<div class="output">
<div id="output">
<div id="text"></div>
<span id="timing"></span>
</div>
</div>
</div>

Html5 canvas image on click

I'm having a problem whit my code.
I draw some circles in a circular path and I expect when to click on them to return something other than 0 in firebug console but that's not happening;
I don't know what is wrong with my code and i hope someone will tell me.
Here's my code:
var canvas, ctx;
var circle_data = [];
function circles(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
circle_data.push(this);
}
circles.prototype = {
draw: function (context) {
context.beginPath();
context.arc(this.x, this.y, this.radius / 5, 0, 2 * Math.PI, false);
context.fillStyle = "red";
context.fill();
}
}
function draw() {
ctx.translate(250, 250);
for (var n = 0; n < 10; n++) {
var radi = (Math.PI / 180);
var x = Math.sin(radi * n * 36) * 70;
var y = Math.cos(radi * n * 36) * 70;
var radius = 50;
var thiscircle = new circles(x, y, radius);
thiscircle.draw(ctx);
}
}
function mouseDown(e) {
var img_data = ctx.getImageData(e.pageX, e.pageY, 1, 1);
console.log(img_data.data[3]);
}
function init() {
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.addEventListener('mousedown', mouseDown, false);
}
init();
It dosen't matter is i use data[3];
I tried whit console.log(img_data.data[0]+" "+img_data.data[1]+" "+img_data.data[2]);
Still getting 0 0 0
Your detecting the mouse position relative to the page and not the canvas, you need to get the position of the canvas on the page and subtract that from the X and Y of the mouse to find you position relative to the canvas. I use functions similar to the ones below when working with canvas.
getOffsetPosition = function(obj){
/*obj is the Canvas element*/
var offsetX = offsetY = 0;
if (obj.offsetParent) {
do {
offsetX += obj.offsetLeft;
offsetY += obj.offsetTop;
}while(obj = obj.offsetParent);
}
return [offsetX,offsetY];
}
getMouse = function(e,canvasElement){
OFFSET = getOffsetPosition(canvasElement);
mouse_x = (e.pageX || (e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft)) - OFFSET[0];
mouse_y = (e.pageY || (e.clientY + document.body.scrollTop + document.documentElement.scrollTop)) - OFFSET[1];
return [mouse_x,mouse_y];
}
The following code works.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<canvas id="canvas" width="500" height="500" style="background-color:#999999;"></canvas>
</body>
<script>
var canvas,ctx;
var circle_data = [];
function circles(x,y,radius)
{
this.x = x;
this.y = y;
this.radius = radius;
circle_data.push(this);
}
circles.prototype = {
draw: function(context){
context.beginPath();
context.arc(this.x, this.y, this.radius / 5, 0, 2* Math.PI, false);
context.fillStyle = "red";
context.fill();
}
}
getOffsetPosition = function(obj){
/*obj is the Canvas element*/
var offsetX = offsetY = 0;
if (obj.offsetParent) {
do {
offsetX += obj.offsetLeft;
offsetY += obj.offsetTop;
}while(obj = obj.offsetParent);
}
return [offsetX,offsetY];
}
getMouse = function(e,canvasElement){
OFFSET = getOffsetPosition(canvasElement);
mouse_x = (e.pageX || (e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft)) - OFFSET[0];
mouse_y = (e.pageY || (e.clientY + document.body.scrollTop + document.documentElement.scrollTop)) - OFFSET[1];
return [mouse_x,mouse_y];
}
function draw(){
ctx.translate(250, 250);
for (var n = 0; n < 10; n++) {
var radi = (Math.PI/180);
var x = Math.sin(radi*n*36)*70;
var y = Math.cos(radi*n*36)*70;
var radius = 50;
var thiscircle = new circles(x,y,radius);
thiscircle.draw(ctx);
}
}
function mouseDown(e)
{
var pos = getMouse(e,ctx.canvas);
var img_data = ctx.getImageData(pos[0],pos[1],1,1);
console.log(img_data.data[3]);
}
function init() {
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
draw();
canvas.addEventListener('mousedown', mouseDown, false);
}
init();
</script>
</html>

Categories

Resources