html canvas Drawing tool and highlight function - javascript

I am a javascript function to copy paste an image from the clipboard to HTML canvas, futher i also have a function to let the user draw(highlight) on the image pasted on the canvas. However, the drawing tool function seems to override the copy paste function as it is anonymous. I need help to make these two functions operate.
this is my function to copy from clipboard.
function CLIPBOARD_CLASS(canvas_id, autoresize) {
alert("BLAH");
var _self = this;
var canvas = document.getElementById(canvas_id);
var ctx = document.getElementById(canvas_id).getContext("2d");
var ctrl_pressed = false;
var reading_dom = false;
var text_top = 15;
var pasteCatcher;
var paste_mode;
//handlers
document.addEventListener('keydown', function (e) {
_self.on_keyboard_action(e);
}, false); //firefox fix
document.addEventListener('keyup', function (e) {
_self.on_keyboardup_action(e);
}, false); //firefox fix
document.addEventListener('paste', function (e) {
_self.paste_auto(e);
}, false); //official paste handler
//constructor - prepare
this.init = function () {
//if using auto
if (window.Clipboard)
return true;
pasteCatcher = document.createElement("div");
pasteCatcher.setAttribute("id", "paste_ff");
pasteCatcher.setAttribute("contenteditable", "");
pasteCatcher.style.cssText = 'opacity:0;position:fixed;top:0px;left:0px;';
pasteCatcher.style.marginLeft = "-20px";
pasteCatcher.style.width = "10px";
document.body.appendChild(pasteCatcher);
document.getElementById('paste_ff').addEventListener('DOMSubtreeModified', function () {
if (paste_mode == 'auto' || ctrl_pressed == false)
return true;
//if paste handle failed - capture pasted object manually
if (pasteCatcher.children.length == 1) {
if (pasteCatcher.firstElementChild.src != undefined) {
//image
_self.paste_createImage(pasteCatcher.firstElementChild.src);
}
}
//register cleanup after some time.
setTimeout(function () {
pasteCatcher.innerHTML = '';
}, 20);
}, false);
}();
//default paste action
this.paste_auto = function (e) {
paste_mode = '';
pasteCatcher.innerHTML = '';
var plain_text_used = false;
if (e.clipboardData) {
var items = e.clipboardData.items;
if (items) {
paste_mode = 'auto';
//access data directly
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
//image
var blob = items[i].getAsFile();
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
this.paste_createImage(source);
}
}
e.preventDefault();
}
else {
//wait for DOMSubtreeModified event
//https://bugzilla.mozilla.org/show_bug.cgi?id=891247
}
}
};
//on keyboard press -
this.on_keyboard_action = function (event) {
k = event.keyCode;
//ctrl
if (k == 17 || event.metaKey || event.ctrlKey) {
if (ctrl_pressed == false)
ctrl_pressed = true;
}
//c
if (k == 86) {
if (document.activeElement != undefined && document.activeElement.type == 'text') {
//let user paste into some input
return false;
}
if (ctrl_pressed == true && !window.Clipboard)
pasteCatcher.focus();
}
};
//on kaybord release
this.on_keyboardup_action = function (event) {
k = event.keyCode;
//ctrl
if (k == 17 || event.metaKey || event.ctrlKey || event.key == 'Meta')
ctrl_pressed = false;
};
//draw image
this.paste_createImage = function (source) {
var pastedImage = new Image();
pastedImage.onload = function () {
if (autoresize == true) {
//resize canvas
canvas.width = pastedImage.width;
canvas.height = pastedImage.height;
}
else {
//clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
ctx.drawImage(pastedImage, 0, 0);
};
pastedImage.src = source;
};
}
This my drawing tool function
if (window.addEventListener) {
window.addEventListener('load', function () {
var canvas, context, canvaso, contexto;
// The active tool instance.
var tool;
var tool_default = 'line';
function init() {
// Find the canvas element.
canvaso = document.getElementById('my_canvas_1');
if (!canvaso) {
alert('Error: I cannot find the canvas element!');
return;
}
if (!canvaso.getContext) {
alert('Error: no canvas.getContext!');
return;
}
// Get the 2D canvas context.
contexto = canvaso.getContext('2d');
if (!contexto) {
alert('Error: failed to getContext!');
return;
}
// Add the temporary canvas.
var container = canvaso.parentNode;
canvas = document.createElement('canvas');
if (!canvas) {
alert('Error: I cannot create a new canvas element!');
return;
}
canvas.id = 'imageTemp';
canvas.width = canvaso.width;
canvas.height = canvaso.height;
container.appendChild(canvas);
context = canvas.getContext('2d');
// Get the tool select input.
var tool_select = document.getElementById('dtool');
if (!tool_select) {
alert('Error: failed to get the dtool element!');
return;
}
tool_select.addEventListener('change', ev_tool_change, false);
// Activate the default tool.
if (tools[tool_default]) {
tool = new tools[tool_default]();
tool_select.value = tool_default;
}
// Attach the mousedown, mousemove and mouseup event listeners.
canvas.addEventListener('mousedown', ev_canvas, false);
canvas.addEventListener('mousemove', ev_canvas, false);
canvas.addEventListener('mouseup', ev_canvas, false);
}
// The general-purpose event handler. This function just determines the mouse
// position relative to the canvas element.
function ev_canvas(ev) {
if (ev.layerX || ev.layerX == 0) { // Firefox
ev._x = ev.layerX;
ev._y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
ev._x = ev.offsetX;
ev._y = ev.offsetY;
}
// Call the event handler of the tool.
var func = tool[ev.type];
if (func) {
func(ev);
}
}
// The event handler for any changes made to the tool selector.
function ev_tool_change(ev) {
if (tools[this.value]) {
tool = new tools[this.value]();
}
}
// This function draws the #imageTemp canvas on top of #my_cavas_1, after which
// #imageTemp is cleared. This function is called each time when the user
// completes a drawing operation.
function img_update() {
contexto.drawImage(canvas, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
}
// This object holds the implementation of each drawing tool.
var tools = {};
// The drawing pencil.
tools.pencil = function () {
var tool = this;
this.started = false;
// This is called when you start holding down the mouse button.
// This starts the pencil drawing.
this.mousedown = function (ev) {
context.beginPath();
context.moveTo(ev._x, ev._y);
tool.started = true;
};
// This function is called every time you move the mouse. Obviously, it only
// draws if the tool.started state is set to true (when you are holding down
// the mouse button).
this.mousemove = function (ev) {
if (tool.started) {
context.lineTo(ev._x, ev._y);
context.stroke();
}
};
// This is called when you release the mouse button.
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
// The rectangle tool.
tools.rect = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
};
this.mousemove = function (ev) {
if (!tool.started) {
return;
}
var x = Math.min(ev._x, tool.x0),
y = Math.min(ev._y, tool.y0),
w = Math.abs(ev._x - tool.x0),
h = Math.abs(ev._y - tool.y0);
context.clearRect(0, 0, canvas.width, canvas.height);
if (!w || !h) {
return;
}
context.strokeRect(x, y, w, h);
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
// The line tool.
tools.line = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
};
this.mousemove = function (ev) {
if (!tool.started) {
return;
}
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(tool.x0, tool.y0);
context.lineTo(ev._x, ev._y);
context.stroke();
context.closePath();
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
init();
}, false);
}
This is my HTML CANVAS TAG
<canvas id="my_canvas_1" width="300" height="300" onclick="CLIPBOARD_CLASS('my_canvas_1',true);"></canvas>

Related

Canvas touch event js

hi guys I need some help with my canvas, I try differeent ways to make it work in mobile devices but I can't.
I try to launch the methodes that I create to start and stop the click events. But I think is not the rigth way.
class Canvas {
constructor(emplacement, btnEffacer, btnCroix) {
//btn pour effacer et afficher
this.btnCroix = document.querySelector(".fermeture")
this.btnEffacer = document.querySelector(btnEffacer);
// emplacement du canvas
this.canvas = document.querySelector(emplacement);
this.cont = this.canvas.getContext("2d");
//quelques variables
this.signer = false;
this.vide = true
this.canvas.width = 190;
this.canvas.height = 120;
this.cont.lineWidth = 2;
this.cont.strokeStyle = "#000";
//les evenements
//comencer a dessigner
this.canvas.addEventListener("touchstart", this.touchstart.bind(this), false);
this.canvas.addEventListener("touchmove", this.touchmove.bind(this), false);
this.canvas.addEventListener("touchend", this.touchend.bind(this), false);
this.canvas.addEventListener("mousedown", this.demarrer.bind(this));
//arreter de dessigner
this.canvas.addEventListener("mouseup", this.arreter.bind(this));
//le trece du dessin
this.canvas.addEventListener("mousemove", this.dessiner.bind(this));
//effacer le dessin
this.btnCroix.addEventListener("click", this.effacer.bind(this));
this.btnEffacer.addEventListener("click", this.effacer.bind(this));
}
//les methodes
touchstart(e) {
e.preventDefault()
const touche = e.touches[0]
this.demarrer(e)
}
touchmove(e) {
e.preventDefault()
const touche = e.touches[0]
this.dessiner(e)
}
touchend(e) {
e.preventDefault()
this.arreter(e)
}
demarrer(e) {
this.signer = true;
this.vide = false
this.dessiner(e);
}
arreter(e) {
this.signer = false;
this.cont.beginPath();
}
dessiner(e) {
if (!this.signer) return;
this.cont.lineTo(e.offsetX, e.offsetY);
this.cont.stroke();
this.cont.beginPath();
this.cont.moveTo(e.offsetX, e.offsetY);
}
effacer() {
this.cont.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.vide = true
}
If you can explain me how it works and help me with the code, it will be great.
thanks for your help
It seems like you may be the keyword 'on' before your touch events.
The following three lines in your code:
this.canvas.addEventListener("touchstart", this.touchstart.bind(this), false);
this.canvas.addEventListener("touchmove", this.touchmove.bind(this), false);
this.canvas.addEventListener("touchend", this.touchend.bind(this), false);
Should actually be:
this.canvas.addEventListener("ontouchstart", this.touchstart.bind(this), false);
this.canvas.addEventListener("ontouchmove", this.touchmove.bind(this), false);
this.canvas.addEventListener("ontouchend", this.touchend.bind(this), false);
https://www.w3schools.com/jsref/obj_touchevent.asp
This page has a canvas you can draw on with your finger or mouse:
<!doctype html>
<html><head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
</head><body>
<canvas id='thecanvas' width='700' height='1000' style='touch-action:none;border:1px solid #cccccc;'></canvas>
<script>
let canvas = document.getElementById('thecanvas');
function canvas_read_mouse(canvas, e) {
let canvasRect = canvas.getBoundingClientRect();
canvas.tc_x1 = canvas.tc_x2;
canvas.tc_y1 = canvas.tc_y2;
canvas.tc_x2 = e.clientX - canvasRect.left;
canvas.tc_y2 = e.clientY - canvasRect.top;
}
function on_canvas_mouse_down(e) {
canvas_read_mouse(canvas, e);
canvas.tc_md = true;
}
function on_canvas_mouse_up(e) {
canvas.tc_md = false;
}
function on_canvas_mouse_move(e) {
canvas_read_mouse(canvas, e);
if (canvas.tc_md && (canvas.tc_x1 !== canvas.tc_x2 || canvas.tc_y1 !== canvas.tc_y2)) {
let ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(canvas.tc_x1, canvas.tc_y1);
ctx.lineTo(canvas.tc_x2, canvas.tc_y2);
ctx.stroke();
}
}
function canvas_read_touch(canvas, e) {
let canvasRect = canvas.getBoundingClientRect();
let touch = event.touches[0];
canvas.tc_x1 = canvas.tc_x2;
canvas.tc_y1 = canvas.tc_y2;
canvas.tc_x2 = touch.pageX - document.documentElement.scrollLeft - canvasRect.left;
canvas.tc_y2 = touch.pageY - document.documentElement.scrollTop - canvasRect.top;
}
function on_canvas_touch_start(e) {
canvas_read_touch(canvas, e);
canvas.tc_md = true;
}
function on_canvas_touch_end(e) {
canvas.tc_md = false;
}
function on_canvas_touch_move(e) {
canvas_read_touch(canvas, e);
if (canvas.tc_md && (canvas.tc_x1 !== canvas.tc_x2 || canvas.tc_y1 !== canvas.tc_y2)) {
//alert(`${canvas.tc_x1} ${canvas.tc_y1} ${canvas.tc_x2} ${canvas.tc_y2}`);
let ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(canvas.tc_x1, canvas.tc_y1);
ctx.lineTo(canvas.tc_x2, canvas.tc_y2);
ctx.stroke();
}
}
canvas.addEventListener('mousedown', (e) => { on_canvas_mouse_down(e) }, false);
canvas.addEventListener('mouseup', (e) => { on_canvas_mouse_up(e) }, false);
canvas.addEventListener('mousemove', (e) => { on_canvas_mouse_move(e) }, false);
canvas.addEventListener('touchstart', (e) => { on_canvas_touch_start(e) }, false);
canvas.addEventListener('touchend', (e) => { on_canvas_touch_end(e) }, false);
canvas.addEventListener('touchmove', (e) => { on_canvas_touch_move(e) }, false);
</script>
</body></html>

Copy Paste in 2 Different Canvas

My Code works for 1 canvas. But I need this implementation to work for 2 of canvas.
So I tried
var SIGNATURE_2 = new CLIPBOARD_CLASS("signatureCanvas2", true);
The problem is that this always pastes the image in the first canvas, I just need to press Ctrl+V.
How do I paste ONLY when the canvas is focused or hovered?
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copy paste Image to Canvas
////////////////////////////////////////////////////////////////////////////////////////////////////////////
var SIGNATURE = new CLIPBOARD_CLASS("signatureCanvas", true);
var SIGNATURE_2 = new CLIPBOARD_CLASS("signatureCanvas2", true);
/**
* image pasting into canvas
*
* #param {string} canvas_id - canvas id
* #param {boolean} autoresize - if canvas will be resized
*/
function CLIPBOARD_CLASS(canvas_id, autoresize) {
var _self = this;
var canvas = document.getElementById(canvas_id);
var ctx = document.getElementById(canvas_id).getContext("2d");
var ctrl_pressed = false;
var command_pressed = false;
var paste_event_support;
var pasteCatcher;
//handlers
document.addEventListener('keydown', function (e) {
_self.on_keyboard_action(e);
}, false); //firefox fix
document.addEventListener('keyup', function (e) {
_self.on_keyboardup_action(e);
}, false); //firefox fix
document.addEventListener('paste', function (e) {
_self.paste_auto(e);
}, false); //official paste handler
//constructor - we ignore security checks here
this.init = function () {
pasteCatcher = document.createElement("div");
pasteCatcher.setAttribute("id", "paste_ff");
pasteCatcher.setAttribute("contenteditable", "");
pasteCatcher.style.cssText = 'opacity:0;position:fixed;top:0px;left:0px;width:10px;margin-left:-20px;';
document.body.appendChild(pasteCatcher);
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (paste_event_support === true || ctrl_pressed == false || mutation.type != 'childList'){
//we already got data in paste_auto()
return true;
}
//if paste handle failed - capture pasted object manually
if(mutation.addedNodes.length == 1) {
if (mutation.addedNodes[0].src != undefined) {
//image
_self.paste_createImage(mutation.addedNodes[0].src);
}
//register cleanup after some time.
setTimeout(function () {
pasteCatcher.innerHTML = '';
}, 20);
}
});
});
var target = document.getElementById('paste_ff');
var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);
}();
//default paste action
this.paste_auto = function (e) {
paste_event_support = false;
if(pasteCatcher != undefined){
pasteCatcher.innerHTML = '';
}
if (e.clipboardData) {
var items = e.clipboardData.items;
if (items) {
paste_event_support = true;
//access data directly
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
//image
var blob = items[i].getAsFile();
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
this.paste_createImage(source);
}
}
e.preventDefault();
}
else {
//wait for DOMSubtreeModified event
}
}
};
//on keyboard press
this.on_keyboard_action = function (event) {
var k = event.keyCode;
//ctrl
if (k == 17 || event.metaKey || event.ctrlKey) {
if (ctrl_pressed == false)
ctrl_pressed = true;
}
//v
if (k == 86) {
if (document.activeElement != undefined && document.activeElement.type == 'text') {
//let user paste into some input
return false;
}
if (ctrl_pressed == true && pasteCatcher != undefined){
pasteCatcher.focus();
}
}
};
//on kaybord release
this.on_keyboardup_action = function (event) {
//ctrl
if (event.ctrlKey == false && ctrl_pressed == true) {
ctrl_pressed = false;
}
//command
else if(event.metaKey == false && command_pressed == true){
command_pressed = false;
ctrl_pressed = false;
}
};
//draw pasted image to canvas
this.paste_createImage = function (source) {
var pastedImage = new Image();
pastedImage.onload = function () {
if(autoresize == true){
//resize
canvas.width = pastedImage.width;
canvas.height = pastedImage.height;
}
else{
//clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
ctx.drawImage(pastedImage, 0, 0);
};
pastedImage.src = source;
};
}
.signatureCanvas {
border:1px solid #027C8C;
width: 100%;
max-height:200px;
}
<canvas id="signatureCanvas" class="signatureCanvas"></canvas>
<canvas id="signatureCanvas2" class="signatureCanvas"></canvas>
PS: Please just open snipping tool on windows and copy paste an image to test
Detect if mouse is over canvas, and store it in a variable.
var over_canvas=false;
document.getElementById("signatureCanvas").addEventListener("mouseover", function (i) {
over_canvas=true;
});
document.getElementById("signatureCanvas").addEventListener("mouseout", function (i) {
over_canvas=false;
});
When pasting, check if mouse is over canvas by changing your paste function to:
document.addEventListener('paste', function (e) {
if (over_canvas){
_self.paste_auto(e);
}
}, false);

Can Detect Collision but bodies pass through phaser p2 physics

For some reason in my game i can detect collisions but bodies are actually not colliding they are passing through.
This is how i create player:
function createPlayer () {
player = game.add.sprite(200, 200, 'playerimg');
player.anchor.setTo(0.5,0.5);
game.physics.p2.enableBody(player, true);
player.body.data.shapes[0].sensor = true;
game.camera.follow(player);
player.body.onBeginContact.add(player_coll, this);
console.log(player.body)
}
player_coll function fires perfectly fine on collision.
var tree_object = function (id, type, startx, starty, value) {
this.id = id;
this.posx = startx;
this.posy = starty;
this.tree = game.add.sprite(this.posx, this.posy, 'tree');
this.tree.type = 'tree';
this.tree.id = id;
game.physics.p2.enableBody(this.tree, true);
this.tree.body_size = 10;
this.tree.body.data.gravityScale = 0;
this.tree.body.data.shapes[0].sensor = true;
}
function player_coll(body,test){
if(body.sprite.type=="tree"){
console.log(body)
console.log("collided with tree")
}
}
My preload function:
function preload(){
game.stage.disableVisibilityChange = true; // mouse browserdan çıkınca uyutma.2 ekran test için.
game.scale.scaleMode = Phaser.ScaleManager.RESIZE;
game.world.setBounds(0, 0, gameProperties.gameWidth,
gameProperties.gameHeight);
//Fizik için P2JS kullanıcaz.
game.physics.startSystem(Phaser.Physics.P2JS);
//fizik dünyasının sınırlarını yaratır.(duvarlar)
game.physics.p2.setBoundsToWorld(true, true, true, true, true)
//Y nin yerçekimini 0 a eşitle böylece yere düşmeyecek.
game.physics.p2.gravity.y = 0;
// Yerçekimini tamamen kapat.
game.physics.p2.applyGravity = false;
game.physics.p2.enableBody(game.physics.p2.walls, false);
game.load.image('playerimg', '/assets/player.png');
game.load.image('background', 'assets/lake.png');
game.load.image("wood", "/assets/wood.png");
game.load.image("tree", "/assets/tree.png");
// Collision(çarpma) detectionu aç.
game.physics.p2.setImpactEvents(true);
}
As you see in the picture why they are passing through ?

Uncaught Type error: is not a function

I am making a javascript game, using Canvas. It works well superficially, but "Uncaught TypeError: game_state.Update is not a function" keeps going. I cannot know the reason for all day...How can I solve the problem?
error image1, error image2
Suspected files are below.
gfw.js
function onGameInit()
{
document.title = "Lion Travel";
GAME_FPS = 30;
debugSystem.debugMode = true;
//resourcePreLoading
resourcePreLoader.AddImage("/.c9/img/title_background.png");
resourcePreLoader.AddImage("/.c9/img/title_start_off.png");
resourcePreLoader.AddImage("/.c9/img/title_start_on.png");
resourcePreLoader.AddImage("/.c9/img/title_ranking_off.png");
resourcePreLoader.AddImage("/.c9/img/title_ranking_on.png");
resourcePreLoader.AddImage("/.c9/img/game_background_sky.png");
soundSystem.AddSound("/.c9/background.mp3", 1);
after_loading_state = new TitleState();
game_state = TitleState;
setInterval(gameLoop, 1000 / GAME_FPS);
}
window.addEventListener("load", onGameInit, false);
GameFramework.js
window.addEventListener("mousedown", onMouseDown, false);
window.addEventListener("mouseup", onMouseUp, false);
var GAME_FPS;
var game_state;
function onMouseDown(e)
{
if(game_state.onMouseDown != undefined)
game_state.onMouseDown(e);
// alert("x:" + inputSystem.mouseX + " y:" + inputSystem.mouseY);
}
function onMouseUp(e)
{
if(game_state.onMouseUp != undefined)
game_state.onMouseUp(e);
}
function ChangeGameState(nextGameState)
{
if(nextGameState.Init == undefined)
return;
if(nextGameState.Update == undefined)
return;
if(nextGameState.Render == undefined)
return;
game_state = nextGameState;
game_state.Init();
}
function GameUpdate()
{
timerSystem.Update();
**game_state.Update();**
debugSystem.UseDebugMode();
}
function GameRender()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
game_state.Render();
if(debugSystem.debugMode)
{
Context.fillStyle = "#ffffff";
Context.font = '15px Arial';
Context.textBaseline = "top";
Context.fillText("fps: "+ frameCounter.Lastfps, 10, 10);
}
}
function gameLoop()
{
game_state = after_loading_state;
GameUpdate();
GameRender();
frameCounter.countFrame();
}
RS_Title.js
function TitleState()
{
this.imgBackground = resourcePreLoader.GetImage("/.c9/img/title_background.png");
this.imgButtonStartOff = resourcePreLoader.GetImage("/.c9/img/title_start_off.png");
this.imgButtonStartOn = resourcePreLoader.GetImage("/.c9/img/title_start_on.png");
this.imgButtonRankingOff = resourcePreLoader.GetImage("/.c9/img/title_ranking_off.png");
this.imgButtonRankingOn = resourcePreLoader.GetImage("/.c9/img/title_ranking_on.png");
soundSystem.PlayBackgroundMusic("/.c9/background.mp3");
return this;
}
TitleState.prototype.Init = function()
{
soundSystem.PlayBackgroundMusic("/.c9/background.mp3");
};
TitleState.prototype.Render = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackground, 0, 0);
//drawing button
if(inputSystem.mouseX > 170 && inputSystem.mouseX < 170+220
&& inputSystem.mouseY > 480 && inputSystem.mouseY < 480+100)
{
Context.drawImage(this.imgButtonStartOn, 170, 480);
this.flagButtonStart = true;
}
else
{
Context.drawImage(this.imgButtonStartOff, 170, 480);
this.flagButtonStart = false;
}
if(inputSystem.mouseX > 420 && inputSystem.mouseX < 420+220
&& inputSystem.mouseY > 480 && inputSystem.mouseY < 480+100)
{
Context.drawImage(this.imgButtonRankingOn, 420, 480);
this.flagButtonRanking = true;
}
else
{
Context.drawImage(this.imgButtonRankingOff, 420, 480);
this.flagButtonRanking = false;
}
};
TitleState.prototype.Update = function()
{
};
TitleState.prototype.onMouseDown = function()
{
if(this.flagButtonStart)
ChangeGameState(new PlayGameState());
after_loading_state = PlayGameState;
game_state = PlayGameState;
if(this.flagButtonRanking)
ChangeGameState();
};
RS_PlayGame.js
function PlayGameState()
{
this.imgBackgroundSky = resourcePreLoader.GetImage("/.c9/img/game_background_sky.png");
}
PlayGameState.prototype.Init = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackgroundSky, 0, 0);
};
PlayGameState.prototype.Render = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackgroundSky, 0, 0);
};
PlayGameState.prototype.Update = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.drawImage(this.imgBackgroundSky, 0, 0);
};
As mentioned by the others, in the onMouseDown method you are assigning after_loading_state and game_state to PlayGameState which is a function and not an object. So later on when you want to access the Update method, it simply doesn't exist, because it is defined over the object prototype and not the function. You might want to do something like this so that you also avoid instantiating (calling) PlayGameState multiple times:
game_state = new PlayGameState();
ChangeGameState(game_state);
after_loading_state = game_state;

how to pause a html5 canvas javascript animation with a keyboard input

I have a function called drawArc which is animated but I need to be able to pause and unpause with a keyboard input I though I knew how but when I tried this nothing happened. any help would be appreciated. thanks.
if(window.addEventListener)
{
window.addEventListener
( 'load', onLoad, false);
window.addEventListener
('keydown',onKeyDown, false);
}
function onKeyDown(event)
{
var keyCode = event.keyCode;
switch(keyCode)
{
case 80: //p
togglePause();
break;
}
}
function togglePause()
{
if (!Paused)
{
clearInterval(drawArc);
Paused = true;
}
else if (Paused)
{
setInterval(drawArc, time);
Paused = false;
}
}
function onLoad()
{
var canvas;
var context;
var angle = 0;
var time= 20;
var paused = true;
function initialise()
{
canvas = document.getElementById('canvas');
if (!canvas)
{
alert('Error: I cannot find the canvas element!');
return;
}
if (!canvas.getContext)
{
alert('Error: no canvas.getContext!');
return;
}
context = canvas.getContext('2d');
if (!context)
{
alert('Error: failed to getContext!');
return;
}
return setInterval(drawArc, time)
}
Try this: http://jsbin.com/udebiv/2/edit
var canvas
, context
, angle = 0
, time= 20
, paused = false
, timer;
if (window.addEventListener) {
window.addEventListener( 'load', initialise, false);
window.addEventListener('keydown',onKeyDown, false);
}
function onKeyDown(event) {
var keyCode = event.keyCode;
switch(keyCode){
case 80: //p
togglePause();
break;
}
}
function togglePause() {
if (!paused){
clearInterval(timer);
paused = true;
} else {
timer = setInterval(drawArc, time);
paused = false;
}
}
function initialise() {
canvas = document.getElementById('canvas');
if (!canvas){
alert('Error: I cannot find the canvas element!');
return;
}
if (!canvas.getContext){
alert('Error: no canvas.getContext!');
return;
}
context = canvas.getContext('2d');
if (!context){
alert('Error: failed to getContext!');
return;
}
timer = setInterval(drawArc, time)
}
function drawArc(){
// do your drawing here
// I'm just setting body text so you can see togglePause working
document.body.innerHTML = Math.random();
}
There were a few syntax problems that were causing your code from even executing, as well as some issues with variable scoping.

Categories

Resources