I can't reset the image on JavaScript - javascript

I can't reset the image on javascript, codepen say imagem in not defined.
Codepen link: https://codepen.io/AlissonTelez/pen/ExPJBvv
Thats variables:
var originalImage;
var grayImage = null;
var redImage = null;
var rainbowImage = null;
var windowImage = null;
var canvas = document.getElementById("can1");
thats function to make filter red:
function makeRedy() {
if (imgCarregada(imagemRedy)) {
filtroVermelho();
var canNovo = document.getElementById("can");
imagemRedy.drawTo(canvas);
}
}
function filtroVermelho() {
for (var pixel2 of imagemRedy.values()) {
avg2 = (pixel2.getRed()+pixel2.getGreen()+pixel2.getBlue()/3);
if (avg2 < 128) {
pixel2.setRed(2*avg2);
pixel2.setGreen(0);
pixel2.setBlue(0);
}
else {
pixel2.setRed(255);
pixel2.setGreen((2*avg2)-255);
pixel2.setBlue((2*avg2)-255);
}
}
}
that's reset function:
function resete() {
if (imgCarregada(imagem)) {
imagem.drawTo(canvas);
}
}
function imgCarregada(x) {
if (x === null) {
return false;
}
else if (x !== null) {
return true;
}
}

You have not defined imagem. But it appears your original image is being stored as imagemOriginal.
Change your resete() function to this;
function resete() {
if (imgCarregada(imagemOriginal)) {
imagemOriginal.drawTo(canvas);
}
}
Based on your CodePen. Which appears to hold different values to what you pasted in your question.

read my comments in code and try understand what's new
// for checking later if null or not
var imagemOriginal = null;
var imagemRedy = null;
var imagemGray = null;
var avg;
var avg2;
// ctx for canvas api 2d
var canvas , ctx;
function upload() {
var img = document.getElementById("Finput");
canvas = document.getElementById("can");
// defined canvas context 2d for drawing and accessing all canvas api
ctx = canvas.getContext("2d");
imagemOriginal = new SimpleImage(img);
imagemGray = new SimpleImage(img);
imagemRedy = new SimpleImage(img);
imagemOriginal.drawTo(canvas);
}
// calling upload as first step for making canvas ready
upload();
function makeGray() {
if (imgCarregada(imagemGray)) {
filtroCinza();
var canNovo = document.getElementById("can");
imagemGray.drawTo(canvas);
}
}
function filtroCinza() {
for (var pixel of imagemGray.values()) {
avg = (pixel.getRed()+pixel.getGreen()+pixel.getBlue())/3;
pixel.setRed(avg);
pixel.setGreen(avg);
pixel.setBlue(avg);
}
}
function makeRedy() {
if (imgCarregada(imagemRedy)) {
filtroVermelho();
var canNovo = document.getElementById("can");
imagemRedy.drawTo(canvas);
}
}
function filtroVermelho() {
for (var pixel2 of imagemRedy.values()) {
avg2 = (pixel2.getRed()+pixel2.getGreen()+pixel2.getBlue()/3);
if (avg2 < 128) {
pixel2.setRed(2*avg2);
pixel2.setGreen(0);
pixel2.setBlue(0);
}
else {
pixel2.setRed(255);
pixel2.setGreen((2*avg2)-255);
pixel2.setBlue((2*avg2)-255);
}
}
}
// in resete function you put arguments not exist 'imagem' ! and that give you error
// soo sloution is checking 'imagemOriginal'
function resete() {
// soo here do your check // if true call restCanvas for make canvas clear :)
if (imgCarregada(imagemOriginal)) resetCanvas();
}
// this function using 'ctx' or canvas context for make canvas clean
function resetCanvas(){
// fillstyle for select your draw color
ctx.fillStyle = "white";
// fillrect for draw with resloution :)
ctx.fillRect(0,0,canvas.width,canvas.height);
}
// here just syntax better :)
function imgCarregada(x) {
if (x === null) return false;
else if (x !== null) return true;
}

Related

Animated canvas background flashing?

I'm attempting to make a typing game with moving words on a canvas, which move left to right and lives are lost if they leave the canvas however i'm trying to animate a simple looping background image for my canvas, I have gotten it working and looping and moving left, however for some reason when this is in use my entire canvas is flashing as if it is constantly redrawing in a strange way or something I don't really know.
var canvas;
var canvasContext;
let x=20;
var string;
let score = 0;
let highscore = 0;
var lives = 3;
var WordID;
var difficultyWordID
var bg = new Image();
bg.src = "client/img/stars.jpg";
window.onload = function(){
canvas = document.getElementById('typingCanvas');
var typeval = document.getElementById("typingValue"); //user typed value.
canvasContext = canvas.getContext('2d');
document.getElementById("Button2").style.display = "none";
document.getElementById("gameOver").style.display = "none";
document.getElementById("scoreText").style.display = "none";
let fps=40;
setInterval(function(){
if(x==20){
string = getWord()
}
moveEverything()
drawEverything(x,string);
if (x>900) {
lives--;
} else if (lives<1) {
canvas.style.display="none";
document.getElementById("Button2").style.display = "block";
document.getElementById("GameTable").style.display = "none";
document.getElementById("gameHR2").style.display = "none";
document.getElementById("gameHR3").style.display = "none";
document.getElementById("gameOver").style.display = "block";
document.getElementById("scoreText").style.display = "block";
document.getElementById("GameHeading").textContent = "Results below: ";
document.getElementById("scoreText").textContent = "Your Score: " + score;
function updateUserScore() {
fetch("/leaderboard/update", {method: 'post', body: formData}
).then(response => response.json()
).then(responseData => {
if (responseData.hasOwnProperty('error')) {
alert(responseData.error);
} else {
}
});
}
}
if(x>900 || check()){
x=20;
document.getElementById("val").value = ''; //if inputed value get match then blank the input box.
}
},1000/fps)
}
function drawEverything(x,string ){ // draws text etc
canvasContext.fillStyle="rgba(0,0,200,0)"; // background colour
canvasContext.border="white"
canvasContext.fillRect(20,20,canvas.width,canvas.height);
drawString(x,string);
scoreBoard(score);
highScoreBoard(highscore);
}
function moveEverything(){
x+=4; // movement speed of the word
}
function drawString(x,string) {
canvasContext.font="30px Verdana";
canvasContext.fillStyle='gray';
canvasContext.fillText(string,x,280); // place of text appearing.
}
function Background(){ // sets background
this.x = 0, this.y = 0, this.w = bg.width, this.h = bg.height;
this.render = function(){
canvasContext.drawImage(bg, this.x--, 0);
if(this.x <= -499){
this.x = 0;
}
}
}
var background = new Background(); // actual background animation
function animate(){
background.render();
}
var animateInterval = setInterval(animate, 40);
function getWord(WordID) {
WordID = Math.floor(Math.random()*30) +1
difficultyWordID = WordID
if (WordID === null) {
} else
fetch("/words/single/" + WordID, {method: 'get'}
).then(response => response.json()
).then(responseData => {
if (responseData.hasOwnProperty('error')) {
alert(responseData.error);
} else {
string = responseData.Definition;
}
});
}
function check(WordID){
var userVal = document.getElementById("val").value;
if(userVal==string){
return true;
}
return false;
}
function scoreVal(){
if(check()){
fetch("/words/single/" + difficultyWordID, {method: 'get'}
).then(response => response.json()
).then(responseData => {
if (responseData.hasOwnProperty('error')) {
alert(responseData.error);
} else {
let difficultyScore = 1;
difficultyScore = responseData.Difficulty;
score=score + difficultyScore;
}
});
}
}
function highScoreVal(){
if(score>highscore){
highscore=score;
}
}
function scoreBoard(score){
scoreVal(WordID);
canvasContext.fillStyle = "White";
canvasContext.font = "40px hot_sauceitalic";
canvasContext.fillText("Your Score: ",50,60);
canvasContext.fillStyle = "White";
canvasContext.fillText(score, 250, 60);
}
function highScoreBoard(highscore){
highScoreVal();
canvasContext.fillStyle = "White";
canvasContext.fillText("Lives:",750,60);
canvasContext.fillStyle = "White";
canvasContext.font = "40px hot_sauceitalic";
canvasContext.fillText(lives, 850, 60);
}
I am unsure how to go about fixing this as I cant really work out the problem myself, I am assuming that it is to do with how it is drawing the background alongside the moving words.
EDIT - Tried using background-image and got this instead.
https://i.stack.imgur.com/UhNai.png

JQuery and XHR Request asyncronious issues

I'm trying to manage to apply an generated image of an audio graph for every div that a music url is found with a Google Chrome Extension.
However, the process of downloading the music from the url and processing the image, takes enough time that all of the images keep applying to the last div.
I'm trying to apply the images to each div as throughout the JQuery's each request. All the div's have the /renderload.gif gif playing, but only the last div flashes as the images finished processing one by one.
Example being that the src is being set to /renderload.gif for all 1,2,3,4,5
but once the sound blob was downloaded and image was generated, only 4-5 gets the images and it continues on loading the queue, repeating the issue.
Here's an example of what I'm trying to deal with.
Here's my latest attempts to add queueing to avoid lag by loading all the audios at once, but it seems the issue still persists.
// context.js
function Queue(){
var queue = [];
var offset = 0;
this.getLength = function(){
return (queue.length - offset);
}
this.isEmpty = function(){
return (queue.length == 0);
}
this.setEmpty = function(){
queue = [];
return true;
}
this.enqueue = function(item){
queue.push(item);
}
this.dequeue = function(){
if (queue.length == 0) return undefined;
var item = queue[offset];
if (++ offset * 2 >= queue.length){
queue = queue.slice(offset);
offset = 0;
}
return item;
}
this.peek = function(){
return (queue.length > 0 ? queue[offset] : undefined);
}
}
var audioqueue=new Queue();
var init=0;
var current=0;
var finished=0;
function RunGraphs(x) {
if (x==init) {
if (audioqueue.isEmpty()==false) {
current++;
var das=audioqueue.dequeue();
var divparent=das.find(".original-image");
var songurl=das.find(".Mpcs").find('span').attr("data-url");
console.log("is song url "+songurl);
console.log("is data here "+divparent.attr("title"));
divparent.css('width','110px');
divparent.attr('src','https://i.pinimg.com/originals/a4/f2/cb/a4f2cb80ff2ae2772e80bf30e9d78d4c.gif');
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET",songurl,true);
xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
xhr.onload = function() {
blob = xhr.response;//xhr.response is now a blob object
console.log(blob);
SCWFRobloxAudioTool.generate(blob, {
canvas_width: 110,
canvas_height: 110,
bar_width: 1,
bar_gap : .2,
wave_color: "#ecb440",
download: false,
onComplete: function(png, pixels) {
if (init == x) {
divparent.attr('src',png);
finished++;
}
}
});
}
xhr.send();
OnHold(x);
}
}
}
function OnHold(x) {
if (x==init) {
if (current > finished+7) {
setTimeout(function(){
OnHold(x)
},150)
} else {
RunGraphs(x)
}
}
}
if (window.location.href.includes("/lib?Ct=DevOnly")){
functionlist=[];
current=0;
finished=0;
init++;
audioqueue.setEmpty();
$(".CATinner").each(function(index) {
(function(x){
audioqueue.enqueue(x);
}($(this)));
});
RunGraphs(init);
};
The SCWFAudioTool is from this github repository.
Soundcloud Waveform Generator
The Queue.js from a search request, slightly modified to have setEmpty support.Queue.js
Please read the edit part of the post
I mad a usable minimal example of your code in order to check your Queue and defer method. there seems to be no error that i can find (i don't have the html file and cant check for missing files. Please do that yourself by adding the if (this.status >= 200 && this.status < 400) check to the onload callback):
// context.js
function Queue(){
var queue = [];
var offset = 0;
this.getLength = function(){
return (queue.length - offset);
}
this.isEmpty = function(){
return (queue.length == 0);
}
this.setEmpty = function(){
queue = [];
return true;
}
this.enqueue = function(item){
queue.push(item);
}
this.dequeue = function(){
if (queue.length == 0) return undefined;
var item = queue[offset];
if (++ offset * 2 >= queue.length){
queue = queue.slice(offset);
offset = 0;
}
return item;
}
this.peek = function(){
return (queue.length > 0 ? queue[offset] : undefined);
}
}
var audioqueue=new Queue();
var init=0;
var current=0;
var finished=0;
function RunGraphs(x) {
if (x==init) {
if (audioqueue.isEmpty()==false) {
current++;
var songurl = audioqueue.dequeue();
console.log("is song url "+songurl);
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET",songurl,true);
xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
xhr.onload = function() {
if (this.status >= 200 && this.status < 400) {
blob = xhr.response;//xhr.response is now a blob object
console.log('OK');
finished++;
} else {
console.log('FAIL');
}
}
xhr.send();
OnHold(x);
}
}
}
function OnHold(x) {
if (x==init) {
if (current > finished+7) {
setTimeout(function(){
OnHold(x)
},150)
} else {
RunGraphs(x)
}
}
}
var demoObject = new Blob(["0".repeat(1024*1024*2)]); // 2MB Blob
var demoObjectURL = URL.createObjectURL(demoObject);
if (true){
functionlist=[];
current=0;
finished=0;
init++;
audioqueue.setEmpty();
for(var i = 0; i < 20; i++)
audioqueue.enqueue(demoObjectURL);
RunGraphs(init);
};
Therefore if there are no errors left concerning missing files the only errors i can think off is related to the SCWFRobloxAudioTool.generate method.
Please check if the callback gets triggered correctly and that no errors accrue during conversion.
If you provide additional additional info, data or code i can look into this problem.
EDIT:
I looked into the 'SoundCloudWaveform' program and i think i see the problem:
The module is not made to handle multiple queries at once (there is only one global setting object. So every attempt to add another query to the api will override the callback of the previous one, and since the fileReader is a async call only the latest added callback will be executed.)
Please consider using an oop attempt of this api:
window.AudioContext = window.AudioContext || window.webkitAudioContext;
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
function SoundCloudWaveform (){
this.settings = {
canvas_width: 453,
canvas_height: 66,
bar_width: 3,
bar_gap : 0.2,
wave_color: "#666",
download: false,
onComplete: function(png, pixels) {}
}
this.generate = function(file, options) {
// preparing canvas
this.settings.canvas = document.createElement('canvas');
this.settings.context = this.settings.canvas.getContext('2d');
this.settings.canvas.width = (options.canvas_width !== undefined) ? parseInt(options.canvas_width) : this.settings.canvas_width;
this.settings.canvas.height = (options.canvas_height !== undefined) ? parseInt(options.canvas_height) : this.settings.canvas_height;
// setting fill color
this.settings.wave_color = (options.wave_color !== undefined) ? options.wave_color : this.settings.wave_color;
// setting bars width and gap
this.settings.bar_width = (options.bar_width !== undefined) ? parseInt(options.bar_width) : this.settings.bar_width;
this.settings.bar_gap = (options.bar_gap !== undefined) ? parseFloat(options.bar_gap) : this.settings.bar_gap;
this.settings.download = (options.download !== undefined) ? options.download : this.settings.download;
this.settings.onComplete = (options.onComplete !== undefined) ? options.onComplete : this.settings.onComplete;
// read file buffer
var reader = new FileReader();
var _this = this;
reader.onload = function(event) {
var audioContext = new AudioContext()
audioContext.decodeAudioData(event.target.result, function(buffer) {
audioContext.close();
_this.extractBuffer(buffer);
});
};
reader.readAsArrayBuffer(file);
}
this.extractBuffer = function(buffer) {
buffer = buffer.getChannelData(0);
var sections = this.settings.canvas.width;
var len = Math.floor(buffer.length / sections);
var maxHeight = this.settings.canvas.height;
var vals = [];
for (var i = 0; i < sections; i += this.settings.bar_width) {
vals.push(this.bufferMeasure(i * len, len, buffer) * 10000);
}
for (var j = 0; j < sections; j += this.settings.bar_width) {
var scale = maxHeight / vals.max();
var val = this.bufferMeasure(j * len, len, buffer) * 10000;
val *= scale;
val += 1;
this.drawBar(j, val);
}
if (this.settings.download) {
this.generateImage();
}
this.settings.onComplete(this.settings.canvas.toDataURL('image/png'), this.settings.context.getImageData(0, 0, this.settings.canvas.width, this.settings.canvas.height));
// clear canvas for redrawing
this.settings.context.clearRect(0, 0, this.settings.canvas.width, this.settings.canvas.height);
},
this.bufferMeasure = function(position, length, data) {
var sum = 0.0;
for (var i = position; i <= (position + length) - 1; i++) {
sum += Math.pow(data[i], 2);
}
return Math.sqrt(sum / data.length);
},
this.drawBar = function(i, h) {
this.settings.context.fillStyle = this.settings.wave_color;
var w = this.settings.bar_width;
if (this.settings.bar_gap !== 0) {
w *= Math.abs(1 - this.settings.bar_gap);
}
var x = i + (w / 2),
y = this.settings.canvas.height - h;
this.settings.context.fillRect(x, y, w, h);
},
this.generateImage = function() {
var image = this.settings.canvas.toDataURL('image/png');
var link = document.createElement('a');
link.href = image;
link.setAttribute('download', '');
link.click();
}
}
console.log(new SoundCloudWaveform());
Also consider simply using an array for the queue:
function Queue(){
var queue = [];
var offset = 0;
this.getLength = function(){
return (queue.length - offset);
}
this.isEmpty = function(){
return (queue.length == 0);
}
this.setEmpty = function(){
queue = [];
return true;
}
this.enqueue = function(item){
queue.push(item);
}
this.dequeue = function(){
if (queue.length == 0) return undefined;
var item = queue[offset];
if (++ offset * 2 >= queue.length){
queue = queue.slice(offset);
offset = 0;
}
return item;
}
this.peek = function(){
return (queue.length > 0 ? queue[offset] : undefined);
}
}
var q = new Queue();
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
console.log(q.dequeue());
console.log(q.dequeue());
console.log(q.dequeue());
console.log(q.dequeue());
var q2 = [];
q2.push(1)
q2.push(2)
q2.push(3)
console.log(q2.shift());
console.log(q2.shift());
console.log(q2.shift());
console.log(q2.shift());
It prevents confusion ant the speedup of it is minimal in your application.
On your open method on the xhr object, set the parameter to true, also... try using the onload() instead of onloadend(). Good Luck!
var xmlhttp = new XMLHttpRequest(),
method = 'GET',
url = 'https://developer.mozilla.org/';
xmlhttp.open(method, url, true);
xmlhttp.onload = function () {
// Do something with the retrieved data
};
xmlhttp.send();

I'm trying to convert a HTML canvas to a HTML image, but I'm getting a blank image

In my application I generate a circle using the HTML element canvas.
The generation of the circle works well: the circle is correctly rendered.
The problem is that I have to put that circle in an option of a select, and as far as I know is not possible to put a canvas inside an option, therefore I probably have to convert the canvas to a base64 image so that I should be able to use it as a background-image of the option.
However, the conversion from canvas to base64 image is not working, as the browser is rendering a blank image.
I have created a fiddle for troubleshooting: https://jsfiddle.net/4hfmp0cs/
Here below you can see the javascript code of the fiddle.
function foo()
{
var circle = getStateCircle("opened");
//var gl = circle.getContext("webgl", { preserveDrawingBuffer: true });
var dataUrl = circle.toDataURL("image/png");
var img = document.createElement("img");
img.src = dataUrl;
document.getElementById("container").appendChild(img);
}
function getStateCircle(state)
{
var stateCircle;
if(state === "opened")
{
stateCircle = new Circle("#ffcc00", "20px");
}
else if(state === "accepted")
{
stateCircle = new Circle("#33cc33", "20px");
}
else if (state === "refused")
{
stateCircle = new Circle("#ff3300", "20px");
}
else if (state === "closed")
{
stateCircle = new Circle("black", "20px");
}
else
{
throw new Error("The state of the offer is unknown");
}
stateCircle.buildCircle();
var circle = stateCircle.getCircle();
return circle;
}
function Circle(color, size)
{
this._color = color;
this._size = size;
this._circle;
this.buildCircle = function()
{
var style = {
borderRadius: "50%",
backgroundColor: this._color,
height: this._size,
width: this._size
}
this._circle = new ElementBuilder("canvas").withStyleObject(style).getElement();
}
this.buildCircleAndAppendTo = function(father)
{
this._buildCircle();
father.appendChild(this._circle);
}
this.getCircle = function()
{
return this._circle;
}
}
function ElementBuilder(elementName) {
var This = this;
this.element = document.createElement(elementName);
this.withName = function (name)
{
this.element.setAttribute("name", name);
return this;
};
this.withAttribute = function (attributeName, attributeValue)
{
this.element.setAttribute(attributeName, attributeValue);
return this;
};
this.withId = function (id)
{
this.element.setAttribute("id", id);
return this;
}
this.withClass = function (className)
{
this.element.setAttribute("class", className);
return this;
}
this.addClass = function (className)
{
this.element.className = this.element.className + " " + className;
return this;
}
this.withTextContent = function (text)
{
this.element.textContent = text;
return this;
}
this.withValue = function (value)
{
this.element.value = value;
return this;
}
this.getElement = function ()
{
return this.element;
};
this.withChild = function (child)
{
this.element.appendChild(child);
return this;
};
this.withEventListener = function (type, func)
{
this.element.addEventListener(type, func);
return this;
};
this.withClickEventListener = function (func)
{
this.element.addEventListener("click", func);
return this;
}
this.withDoubleClickEventListener = function (func)
{
this.element.addEventListener("dblclick", func);
return this;
}
this.withStyle = function (styleAttribute, value)
{
this.element.style[styleAttribute] = value;
return this;
}
this.withStyleObject = function (styleObject)
{
ensureIsAnObject(styleObject);
var keys = Object.keys(styleObject);
keys.forEach(function (elt) {
This.withStyle(elt, styleObject[elt]);
});
return this;
}
}
function ensureIsAnObject(value, argumentName) {
if (!(typeof value == "object")) {
throw new Error("The argument '" + argumentName + "' should be an object, but it's type is --->" + typeof value);
}
}
The HTML code
<div id="container">
</div>
<button onclick="foo()">Append image</button>
Nowhere are you actually drawing to the canvas, just styling it with css, which is rendered separate from the canvas. You can replace the canvas with a div, or any other block element and just append that to the document to get the correct effect.
Converts canvas to an image
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
Or Check in
http://jsfiddle.net/simonsarris/vgmFN/

JavaScript with PHP SESSION

I have a problem because I can not add php session to post in javascript, or do not know how to do it, here is my code which is a problem.
if (!this.movesAvailable()) {
var xmlhttp = null;
this.over = true; // Game over!
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://obiektywnywaper.pl/2048/post.php?user=&wynik="+self.score, true);
xmlhttp.send();
alert(self.score);
}
I tried something like this, but it does not work
if (!this.movesAvailable()) {
var xmlhttp = null;
var user=<?echo $_SESSION['user'];?>;
this.over = true; // Game over!
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://obiektywnywaper.pl/2048/post.php?user="+user+"&wynik="+self.score, true);
xmlhttp.send();
alert(self.score);
}
I add also the js file
function GameManager(size, InputManager, Actuator, ScoreManager) {
this.size = size; // Size of the grid
this.inputManager = new InputManager;
this.scoreManager = new ScoreManager;
this.actuator = new Actuator;
this.startTiles = 2;
this.inputManager.on("move", this.move.bind(this));
this.inputManager.on("restart", this.restart.bind(this));
this.inputManager.on("keepPlaying", this.keepPlaying.bind(this));
this.inputManager.on("showInfo", this.showInfo.bind(this));
this.inputManager.on("hideInfo", this.hideInfo.bind(this));
this.setup();
}
// Restart the game
GameManager.prototype.restart = function () {
this.actuator.continue();
this.setup();
};
// Keep playing after winning
GameManager.prototype.keepPlaying = function () {
this.keepPlaying = true;
this.actuator.continue();
};
GameManager.prototype.showInfo = function () {
this.actuator.showInfo();
};
GameManager.prototype.hideInfo = function () {
this.actuator.hideInfo();
};
GameManager.prototype.isGameTerminated = function () {
if (this.over || (this.won && !this.keepPlaying)) {
return true;
} else {
return false;
}
};
// Set up the game
GameManager.prototype.setup = function () {
this.grid = new Grid(this.size);
this.score = 0;
this.over = false;
this.won = false;
this.keepPlaying = false;
// Add the initial tiles
this.addStartTiles();
// Update the actuator
this.actuate();
};
// Set up the initial tiles to start the game with
GameManager.prototype.addStartTiles = function () {
for (var i = 0; i < this.startTiles; i++) {
this.addRandomTile();
}
};
// Adds a tile in a random position
GameManager.prototype.addRandomTile = function () {
if (this.grid.cellsAvailable()) {
var value = Math.random() < 0.9 ? 2 : 4;
var tile = new Tile(this.grid.randomAvailableCell(), value);
this.grid.insertTile(tile);
}
};
// Sends the updated grid to the actuator
GameManager.prototype.actuate = function () {
if (this.scoreManager.get() < this.score) {
this.scoreManager.set(this.score);
}
this.actuator.actuate(this.grid, {
score: this.score,
over: this.over,
won: this.won,
bestScore: this.scoreManager.get(),
terminated: this.isGameTerminated()
});
};
// Save all tile positions and remove merger info
GameManager.prototype.prepareTiles = function () {
this.grid.eachCell(function (x, y, tile) {
if (tile) {
tile.mergedFrom = null;
tile.savePosition();
}
});
};
// Move a tile and its representation
GameManager.prototype.moveTile = function (tile, cell) {
this.grid.cells[tile.x][tile.y] = null;
this.grid.cells[cell.x][cell.y] = tile;
tile.updatePosition(cell);
};
// Move tiles on the grid in the specified direction
GameManager.prototype.move = function (direction) {
// 0: up, 1: right, 2:down, 3: left
var self = this;
if (this.isGameTerminated()) return; // Don't do anything if the game's over
var cell, tile;
var vector = this.getVector(direction);
var traversals = this.buildTraversals(vector);
var moved = false;
// Save the current tile positions and remove merger information
this.prepareTiles();
// Traverse the grid in the right direction and move tiles
traversals.x.forEach(function (x) {
traversals.y.forEach(function (y) {
cell = { x: x, y: y };
tile = self.grid.cellContent(cell);
if (tile) {
var positions = self.findFarthestPosition(cell, vector);
var next = self.grid.cellContent(positions.next);
// Only one merger per row traversal?
if (next && next.value === tile.value && !next.mergedFrom) {
var merged = new Tile(positions.next, tile.value * 2);
merged.mergedFrom = [tile, next];
self.grid.insertTile(merged);
self.grid.removeTile(tile);
// Converge the two tiles' positions
tile.updatePosition(positions.next);
// Update the score
self.score += merged.value;
// The mighty 2048 tile
if (merged.value === 2048) self.won = true;
} else {
self.moveTile(tile, positions.farthest);
}
if (!self.positionsEqual(cell, tile)) {
moved = true; // The tile moved from its original cell!
}
}
});
});
if (moved) {
this.addRandomTile();
if (!this.movesAvailable()) {
var xmlhttp = null;
this.over = true; // Game over!
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://obiektywnywaper.pl/2048/post.php?user=&wynik="+self.score, true);
xmlhttp.send();
alert(self.score);
}
this.actuate();
}
};
// Get the vector representing the chosen direction
GameManager.prototype.getVector = function (direction) {
// Vectors representing tile movement
var map = {
0: { x: 0, y: -1 }, // up
1: { x: 1, y: 0 }, // right
2: { x: 0, y: 1 }, // down
3: { x: -1, y: 0 } // left
};
return map[direction];
};
// Build a list of positions to traverse in the right order
GameManager.prototype.buildTraversals = function (vector) {
var traversals = { x: [], y: [] };
for (var pos = 0; pos < this.size; pos++) {
traversals.x.push(pos);
traversals.y.push(pos);
}
// Always traverse from the farthest cell in the chosen direction
if (vector.x === 1) traversals.x = traversals.x.reverse();
if (vector.y === 1) traversals.y = traversals.y.reverse();
return traversals;
};
GameManager.prototype.findFarthestPosition = function (cell, vector) {
var previous;
// Progress towards the vector direction until an obstacle is found
do {
previous = cell;
cell = { x: previous.x + vector.x, y: previous.y + vector.y };
} while (this.grid.withinBounds(cell) &&
this.grid.cellAvailable(cell));
return {
farthest: previous,
next: cell // Used to check if a merge is required
};
};
GameManager.prototype.movesAvailable = function () {
return this.grid.cellsAvailable() || this.tileMatchesAvailable();
};
// Check for available matches between tiles (more expensive check)
GameManager.prototype.tileMatchesAvailable = function () {
var self = this;
var tile;
for (var x = 0; x < this.size; x++) {
for (var y = 0; y < this.size; y++) {
tile = this.grid.cellContent({ x: x, y: y });
if (tile) {
for (var direction = 0; direction < 4; direction++) {
var vector = self.getVector(direction);
var cell = { x: x + vector.x, y: y + vector.y };
var other = self.grid.cellContent(cell);
if (other && other.value === tile.value) {
return true; // These two tiles can be merged
}
}
}
}
}
return false;
};
GameManager.prototype.positionsEqual = function (first, second) {
return first.x === second.x && first.y === second.y;
};
I don't know php, but classic asp works in similar fashion as far as I know. If you set the variable outside the scope of the function, and also include apostrophes, it should work.
var user="<?php echo $_SESSION['user'];?>"; //possibly declared outside of scope
Edited as per #developerwjk's comment about the php-syntax

how to get the copy of object which is clicked

Hello every one i am currently working with html5 and easelJS.I have a canvas and an images on it.What I want is that when I click on the image its copy is created and and when I click on some other place at canvas my images is copied there so leaving two images on my canvas.
I want to ask is there a way by which I can know that whether I am clicking on the image or or on the canvas.and How to make a copy of my image as I have wrote some code but it removes my orignal image and place it to ther place leaving only one image on the canvas
thanks
You can solve this by storing the image that your bitmaps are built from, then re-adding them when you need to paste. Also you'll need to override Stage.prototype._handleMouseDown like this:
window.Stage.prototype._handleMouseDown = function(e){
if (this.onMouseDown) {
this.onMouseDown(new MouseEvent("onMouseDown", this.mouseX, this.mouseY, this, e));
}
var target = this._getObjectsUnderPoint(this.mouseX, this.mouseY, null, (this._mouseOverIntervalID ? 3 : 1));
if (target) {
if (target.onPress instanceof Function) {
var evt = new MouseEvent("onPress", this.mouseX, this.mouseY, target, e);
target.onPress(evt);
if (evt.onMouseMove || evt.onMouseUp) { this._activeMouseEvent = evt; }
}
this._activeMouseTarget = target;
} else {
this.onPressThrough && this.onPressThrough(e);
}
}
Then in your implementation define onPressThrough like this.
stage.onPressThrough = function(event){
console.log("paste");
paste(event.x, event.y);
}
Here is a complete working example:
$(document).ready(
function(){
var canvas = document.createElement('canvas');
$(canvas).attr('width', '1000');
$(canvas).attr('height', '1000');
$('body').append(canvas);
var stage = window.stage = new Stage(canvas);
canvas.stage = stage;
function copy(target){
window.clipboard = target;
}
function addImage(image, x, y){
var bitmap = new Bitmap(image);
bitmap.image = image;
bitmap.onPress = function(event){
console.log("copy")
copy(this.image);
}
stage.addChild(bitmap);
bitmap.x = x || 0;
bitmap.y = y || 0;
}
function paste(x, y){
window.clipboard && addImage(clipboard, x, y);
}
window.Stage.prototype._handleMouseDown = function(e){
if (this.onMouseDown) {
this.onMouseDown(new MouseEvent("onMouseDown", this.mouseX, this.mouseY, this, e));
}
var target = this._getObjectsUnderPoint(this.mouseX, this.mouseY, null, (this._mouseOverIntervalID ? 3 : 1));
if (target) {
if (target.onPress instanceof Function) {
var evt = new MouseEvent("onPress", this.mouseX, this.mouseY, target, e);
target.onPress(evt);
if (evt.onMouseMove || evt.onMouseUp) { this._activeMouseEvent = evt; }
}
this._activeMouseTarget = target;
} else {
this.onPressThrough && this.onPressThrough(e);
}
}
stage.onPressThrough = function(event){
console.log("paste");
paste(event.x, event.y);
}
var image = new Image();
image.src = "assets/images/tempimage.png";
addImage(image);
window.tick = function(){
stage.update();
}
Ticker.addListener(window);
}
)

Categories

Resources