execute drawImage() as function in a class - javascript

I can't draw the image using the function of the class.
I allready tried this.img and var img but they are both not working.
I added an online source of the jquery-libaryto place it online, but on my pc i'm using an offline source that is working!
<!doctype html>
<head>
<link rel="stylesheet" href="js\jquery-ui-1.10.1.custom.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"> </script>
<script type="text/javascript">
var canvas;
var ctx;
var BurgerArray = new Array(50);
function burger()
{
this.x = 10;
this.y = 20;
this.img = new Image();
img.src='Img/Burger1.png';
img.onload = function()
{
}
this.teken = function()
{
ctx.drawImage(img,20,20);
}
}
var b;
$(document).ready(function()
{
canvas =document.getElementById("MyCanvas");
ctx =canvas.getContext("2d");
b = new burger();
b.teken();
});
</script>
<style type="text/css">
#MyCanvas
{
margin:auto;
display:block;
border:dashed;
border-color:#0F0;
}
</style>
</head>
<body style=" width:100%; height:100%;">
<canvas id="MyCanvas" width="1000" height="600"></canvas>
</body>
</html>

When you create a new object, it's scope is different from the global one. Change the implementation to:
function burger(canvas)
{
this.x = 10;
this.y = 20;
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.teken = function() {
this.ctx.drawImage(img,20,20);
};
}
$(document).ready(function() {
var canvas = document.getElementById("MyCanvas");
var b = new burger(canvas);
b.teken();
});

Related

javascript: uncaught reference error

I am making a javascript game, using Canvas. However, I got that error(below image) and background image is not shown. I suspect below 4 files, because other files didn't make any trouble. I guess the problem is related with game_state...how can I solve the problem??
I am agonizing for 2days:( plz, help me..
error image1
error image2
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>Lion Travel</title>
<!--GameFramework-->
<script src="/.c9/gfw/GameFramework.js"></script>
<script src="/.c9/gfw/FrameCounter.js"></script>
<script src="/.c9/gfw/InputSystem.js"></script>
<script src="/.c9/gfw/SoundManager.js"></script>
<script src="/.c9/gfw/GraphicObject.js"></script>
<script src="/.c9/gfw/SpriteAnimation.js"></script>
<script src="/.c9/gfw/ResourcePreLoader.js"></script>
<script src="/.c9/gfw/DebugSystem.js"></script>
<script src="/.c9/gfw/Timer.js"></script>
<script src="/.c9/gfw/FrameSkipper.js"></script>
<script src="/.c9/gfw/TransitionState.js"></script>
<!--GameInit-->
<script src="/.c9/gfw/gfw.js"></script>
<!--Game Logic-->
<script src="/.c9/RS_Title.js"></script>
</head>
<body>
<canvas id="GameCanvas" width="800" height="600">html5 canvas is not supported.</canvas>
</body>
</html>
gfw.js
function onGameInit() {
document.title = "Lion Travel";
GAME_FPS = 30;
debugSystem.debugMode = true;
resourcePreLoader.AddImage("/.c9/title_background.png");
soundSystem.AddSound("/.c9/background.mp3", 1);
after_loading_state = new TitleState();
setInterval(gameLoop, 1000 / GAME_FPS);
}
window.addEventListener("load", onGameInit, false);
RS_Title.js
function TitleState()
{
this.imgBackground = resourcePreLoader.GetImage("/.c9/title_background.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");
//drawing backgroundimage
Context.drawImage(this.imgBackground, 0, 0);
};
TitleState.prototype.Update = function()
{
};
GameFramework.js
var GAME_FPS;
var game_state = after_loading_state;
function ChangeGameState(nextGameState)
{
//checking essential function
if(nextGameState.Init == undefined)
return;
if(nextGameState.Update == undefined)
return;
if(nextGameState.Render == undefined)
return;
game_state = nextGameState;
game_state.Init();
}
function Update()
{
timerSystem.Update();
game_state.Update();
debugSystem.UseDebugMode();
}
function Render()
{
//drawing
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.fillStyle = "#000000";
Context.fillRect(0, 0, 800, 600);
//game state
game_state.Render();
if(debugSystem.debugMode)
{
//showing fps
Context.fillStyle = "#ffffff";
Context.font = '15px Arial';
Context.textBaseline = "top";
Context.fillText("fps: "+ frameCounter.Lastfps, 10, 10);
}
}
function gameLoop()
{
Update();
Render();
frameCounter.countFrame();
}
The issue here is that you are initializing game_state with the object after_loading_state even before after_loading_state is initialized(which is initialized only after the document is loaded). Due to this game_state remains undefined.
To fix this, change var game_state = after_loading_state; in GameFramework.js to var game_state;. And add game_state = after_loading_state; as the first line in gameLoop function. This way, the initialization of variables occur in the correct order.

Insert image from URL into Google Docs

I am trying to get image from external link and add in a document.
Html service work fine. However, document should fill out after onload function.
How can I fix it ?
code.gs
function doGet(e){
var content = HtmlService.createHtmlOutputFromFile('index').getContent();
return HtmlService.createHtmlOutput(content);
}
function im(baseUrl){
var resp = UrlFetchApp.fetch(baseUrl);
var docID = "0000xxxxx1111"
var doc = DocumentApp.openById(docID);
doc.getChild(0).asParagraph().appendInlineImage(resp.getBlob());
return baseUrl;
}
index.html
<!DOCTYPE html>
<head>
<base target="_top">
<script>
window.onload = function() {
var url = "http://xxx.co/image.png"
var canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 100;
document.getElementById('barcode').appendChild(canvas);
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = url;
ctx.drawImage(image, 0, 0);
google.script.run.withSuccessHandler(function(a) {
document.getElementById("imageid").src=a;
}).im(canvas.toDataURL());
}
</script>
</head>
<body>
<img id="imageid" src="" alt="image">
</body>
</html>
There are a few problems with your HTML which is why it probably isn't working. You also had not tagged any elements with the barcode id.
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body id="barcode">
<img id="imageid" src="" alt="image">
</body>
<script>
window.onload = function() {
var url = "http://lorempixel.com/400/200/"
var canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 100;
document.getElementById('barcode').appendChild(canvas);
var ctx = canvas.getContext('2d');
var image = new Image();
image.src = url;
ctx.drawImage(image, 0, 0);
google.script.run.withSuccessHandler(function(a) {
document.getElementById("imageid").src=a;
}).im(canvas.toDataURL());
}
</script>
</html>

I can't see progress in the browsr when trying to make a game

Hi I'm trying to learn game dev with javascript .... When I ope my html file in my browser, it's blank and this is the error I keep on getting...
createjs-2013.12.12.min.js:13 Uncaught TypeError: f.isVisible is not a functionb.draw
# createjs-2013.12.12.min.js:13b.update
# createjs-2013.12.12.min.js:13window.onload # init.js:25 "
var canvas;
var stage ;
var img = new Image();
var bmpSeq;
var text;
window.onload = function()
{
canvas = document.getElementById("myCanvas");
context = canvas.getContext('2d');
context.canvas.width = 900;
context.canvas.height = 500;
stage = new createjs.Stage(canvas);
text = new Text("TEXT HERE","36px Ariel","black");
text.x =100;
text.y = 200;
stage.addChild(text);
var circle = new createjs.Shape();
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
circle.x = 100;
circle.y = 100;
stage.addChild(circle);
stage.update();
//img.onload = ImageLoaded;
//img.src = "assets/dude.png" ;
}
function ImageLoaded(e)
{
//stage = new createjs.Stage("canvas");
var ss = new createjs.SpriteSheet({
images : [img],
frames : {width:32,height:64},
animations: {
face : 4,
walk : [4,8] }
});
//bitmap sequence
//bmp = new createjs.BitmapAnimation(ss);
//bmp.regX = bmp.spriteSheet.frameWidth/2|0; //reg pt in the center of the frame
// bmp.regY = bmp.spriteSheet.frameHeight/2|0;
//bmp.gotoAndPlay("w_r");
//bmp.x = canvas.width/2;
//bmp.y = canvas.height/2;
stage.addChild(ss); //won't do anything yet
//stage.update();
}
<!DOCTYPE html>
<html>
<head>
<title>GAme Trial</title>
<link href="normalize.css" type="text/css" rel="stylesheet" />
<script language="javascript" type="text/javascript" src="http://code.createjs.com/createjs-2013.12.12.min.js" ></script> <!--Getting the Library-->
<script language="javascript" type="text/javascript" src="init.js" ></script>
</head>
<body>
<canvas id="myCanvas"></canvas> <!--graphical surface in which the game is played-->
</body>
</html>
You created a new Text() object, instead of the createjs.Text() object.
Change this
text = new Text("TEXT HERE","36px Ariel","black");
to this
text = new createjs.Text("TEXT HERE","36px Ariel","black");
And you're good to go. Take care to add createjs. before the objects that were made available by that library.

Referencing canvas with button in Javascript

Ok so I'm attempting to have a webpage with two buttons. Each of these buttons, when clicked, creates a new canvas and calls a different draw function. The first draw function would draw large circles where the users mouse is and small ones when the mouse is pressed. The other draw function does the same thing except small circles when the mouse is unpressed and large ones when it is. I'm not having a problem referencing one of these with the button but the other button doesn't seem to call its draw function. sketch2.js seems to be working fine but it seems that the draw function in sketch.js is not being called. Any advice on how I should go about fixing this is greatly appreciated!
Below is my HTML code:
<html>
<head>
<meta charset="UTF-8">
<button id="myBtn">little then big</button>
<div id="holder"></div>
<button id="myBtn2">big then little</button>
<div id="holder2"></div>
<style> body {padding: 0; margin:0;} </style>
</head>
<body>
<script type="text/javascript" src = "/Users/bburke95/Desktop/JS/p5.dom.js"> </script>
<script language="javascript" type="text/javascript" src="../p5.js"></script>
<script language="javascript" type="text/javascript" src="sketch.js"></script>
<script language="javascript" type="text/javascript" src="sketch2.js"></script>
</body>
</html>
This is my sketch.js class
btn = document.getElementById("myBtn");
var q;
btn.onclick = function setup() {
createCanvas(640, 480);
document.getElementById("holder").innerHTML = '<canvas id="myCanvas" width="490" height="220"></canvas>';
q = 1;
set = 0;
}
function draw() {
if (q == 1) {
var x;
var y;
if (mouseIsPressed) {
fill(255);
x = 160;
y = 160;
} else {
fill(0);
x = 80;
y = 80;
}
ellipse(mouseX, mouseY, x, y);
}
}
and this is my sketch2.js class
btn2 = document.getElementById("myBtn2");
var set;
btn2.onclick = function setup() {
createCanvas(640, 480);
document.getElementById("holder2").innerHTML = '<canvas id="myCanvas2" width="490" height="220"></canvas>';
set = 1;
q = 0;
}
function draw() {
if (set == 1) {
var x;
var y;
if (mouseIsPressed) {
fill(0);
x = 80;
y = 80;
} else {
fill(255);
x = 160;
y = 160;
}
ellipse(mouseX, mouseY, x, y);
}
}
If you want to run more than one P5.js processing sketches on the same page, you have to use "instance mode" to ensure that all the functions aren't cluttering the global namespace (which is a good idea anyway) so they don't overwrite one another.
From their Github project, you can instantiate new sketches like this:
var s = function( p ) {
var x = 100;
var y = 100;
p.setup = function() {
p.createCanvas(700, 410);
};
p.draw = function() {
p.background(0);
p.fill(255);
p.rect(x,y,50,50);
};
};
var myp5 = new p5(s);

Display image in canvas with Javascript?

I want to be able to click on a button on my page and load an image into a canvas at some X,Y coordinates?
The following code is what I have below. I would like the image to be in either image/photo.jpg or in the same directory but preferably in a subdirectory of the main page.
**Question: How to make a JPG show up in a canvas with the click of a button on the web page?
Code:
<!DOCTYPE html>
<html>
<script>
function draw(){
var ctx = document.getElementById("myCanvas").getContext("2d");
var img = new Image():
// img.src = "2c.jpg";
img.src = "/images/2c.jpg";
ctx.drawImage(img,0,0);
}
</script>
<body background="Black">
<div align="center">
<button type="button" onclick="draw()">Show Image on Canvas</button>
<canvas id="myCanvas" width="900" height="400" style="border:2px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="20px Arial";
ctx.fillText("Royal Flush $",500,50);
ctx.fillText("Striaght Flush $",500,80);
ctx.fillText("Flush $",500,110);
ctx.fillText("Four of a Kind $",500,140);
ctx.fillText("Full House $",500,170);
ctx.fillText("Three of a Kind $",500,200);
ctx.fillText("Two Pair $",500,230);
ctx.fillText("Pair of ACES $",500,260);
ctx.rect(495,10,270,350);
ctx.stroke();
</script>
</body>
</html>
March 6th, 2014 Code:
How is the following code not working. Do you have to have an ID tag on Canvas. The page will display but for some reason the image will not when the button is clicked. The image is in the same directory that my index.html file is in.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
canvas{
border: 5px solid black;
}
</style>
</html>
<button id="galaxy">Add image #1</button>
<button id="circles">Add image #2</button><span></span>
<canvas width="500" height="500"></canvas>
<script>
var Images = {};
function loadImages(list){
var total = 0;
document.querySelector("span").innerText = "...Loading...";
for(var i = 0; i < list.length; i++){
var img = new Image();
Images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
document.querySelector("span").innerText = "...Loaded.";
}
};
img.src = list[i].url;
}
}
function drawImage(img){
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(Images[img], 0, 0, 50, 50);
}
loadImages([{
name: "2c.jpg",
url: "mp.jpg"
},{
name: "mp.jpg",
url: "mp.jpg"
}]);
document.querySelector("#galaxy").addEventListener("click", function(){
drawImage("galaxy");
});
document.querySelector("#circles").addEventListener("click", function(){
drawImage("weirdCircles");
});
</script>
</html>
Wait till the image is loaded before drawing:
var img = new Image();
img.onload = function(){ /*or*/ img.addEventListener("load", function(){
ctx.drawImage(img,0,0); ctx.drawImage(img,0,0);
}; };
img.src = "/images/2c.jpg";
Demo: http://jsfiddle.net/DerekL/YcLgw/
If you have more than one image in your game,
It is better to preload all images before it starts.
Preload images: http://jsfiddle.net/DerekL/uCQAH/ (Without jQuery: http://jsfiddle.net/DerekL/Lr9Gb/)
If you are more familiar with OOP: http://jsfiddle.net/DerekL/2F2gu/
function ImageCollection(list, callback){
var total = 0, images = {}; //private :)
for(var i = 0; i < list.length; i++){
var img = new Image();
images[list[i].name] = img;
img.onload = function(){
total++;
if(total == list.length){
callback && callback();
}
};
img.src = list[i].url;
}
this.get = function(name){
return images[name] || (function(){throw "Not exist"})();
};
}
//Create an ImageCollection to load and store my images
var images = new ImageCollection([{
name: "MyImage", url: "//example.com/example.jpg"
}]);
//To pick and draw an image from the collection:
var ctx = document.querySelector("canvas").getContext("2d");
ctx.drawImage(images.get("MyImage"), 0, 0);

Categories