Javascript array and object/classes - javascript

i am trying to display three playing cards on the screen and for some reason everytime i run the code a type error appears and i have tried everything to try to fix it but nothing has worked. I think that the problem is in the array/object constructor but i think that everything is right inside of those.
"use strict";
function main(){
var cvs = document.getElementById("foo");
var ctx = foo.getContext("2d");
function Card(posX, posY, imgX, imgY){
this.posX = posX;
this.posY = posY;
this.imgX = imgX;
this.imgY = imgY;
this.width = 97;
this.height = 129;
}
Card.img = new Image();
Card.img.src = "allcards.png";
var cards = [new Card(0,0,0,0), new Card(400,400,194,258), new Card(200,200,291,387)];
var greaterX = false;
var lessX = false;
var greaterY = false;
var lessY = false;
var offsetX;
var offsetY;
setInterval(draw, 10);
function draw(){
ctx.fillStyle="rgb(0,255,255)";
ctx.clearRect(0,0,600,600);
ctx.drawImage(Card.img,cards[1].imgX,cards[1].imgY,Card.width,Card.height,cards[1].posX, cards[1].posY);
ctx.drawImage(Card.img,cards[2].imgX,cards[2].imgY,Card.width,Card.height,cards[2].posX, cards[2].posY);
}
}

var ctx = foo.getContext("2d");
should this not be
var ctx = cvs.getContext("2d");

You seem to have confused the static properties of the Card function object with those of the Card instances - the width and height properties are instance properties.
var cvs = document.getElementById("foo");
var ctx = cvs.getContext("2d");
function Card(posX, posY, imgX, imgY){
this.posX = posX;
this.posY = posY;
this.imgX = imgX;
this.imgY = imgY;
}
// default values/methods, accessible and overwritable on all instances:
Card.prototype.width = 97;
Card.prototype.height = 129;
Card.prototype.draw = function() {
ctx.drawImage(Card.img, this.imgX, this.imgY, this.width, this.height, this.posX, this.posY);
};
// static property:
Card.img = new Image();
Card.img.src = "allcards.png";
Card.img.onload = draw;
var cards = [new Card(0,0,0,0), new Card(400,400,194,258), new Card(200,200,291,387)];
function draw(){
ctx.fillStyle="rgb(0,255,255)";
ctx.clearRect(0,0,600,600);
for (var i=0; i<2; i++)
cards[i].draw();
};

Related

Images not rendering randomly on canvas

Image of the bug is appearing only at one place i.e. x = 0,y = 0.
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
var bugSmashed = 0;
//rendering background image
function renderImage()
{
var backImage = new Image();
backImage.src = "jungle.jpg"
backImage.onload = function(){
c.drawImage(backImage,0,0,canvas.width,canvas.height)}
}
renderImage();
//Making a bug
class Bug {
constructor(x,y){
this.x = x;
this.y = y;
}
renderBug(){
var bugImage = new Image();
bugImage.src = "bug.png";
bugImage.onload = function(){
c.drawImage(bugImage,this.x,this.y,65,65)}}
}
Trying to make the bug appear randomly on the canvas
var interval = setInterval(function(){
var x = 32+Math.random()*(canvas.width-64);
var y = 32+Math.random()*(canvas.height-64);
var aBug = new Bug(x,y);
aBug.renderBug();}, 2000);
I am sure I am missing something. Any help is appreciated. Thanks
I found your problem: this changes its meaning inside a function. So when you use:
function(){c.drawImage(bugImage,this.x,this.y,65,65)}
this no longer refers to aBug! (It will instead refer to the global Window object.) You can use fat-arrow syntax instead (which preserves this):
() => c.drawImage(bugImage,this.x,this.y,65,65)
Another really ugly way which I discourage you from using is by creating a new reference to this, and then using that reference in your function:
let that = this;
function(){ c.drawImage(bugImage, that.x, that.y, 65, 65); };
Or you can simplify your code to have it gloss over onload logic, allowing you to avoid wrapping c.drawImage in a function in the first place (note the square which appears is a publicly addressable image):
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
//Making a bug
let bugImg = new Image();
bugImg.src = "https://th.bing.com/th/id/OIP.pXD0MAw4LeAcVrt3qRiEfwAAAA?pid=ImgDet&rs=1";
class Bug {
constructor(x,y){
this.x = x;
this.y = y;
}
renderBug(){
c.drawImage(bugImg, this.x, this.y, 65, 65);
}
}
var interval = setInterval(function(){
var x = 32 + Math.random()* (canvas.width - 64);
var y = 32 + Math.random()* (canvas.height - 64);
var aBug = new Bug(x, y);
aBug.renderBug();
}, 500);
<canvas id="canvas" width="100" height="100"></canvas>

Fitting Multiple Images on a web page that update from an API

I am Trying to Build a simple web page to display a feed from my cameras that pulls a still image from the camera via the cameras api and then regrabs the image with the API (so i can configure the frame rate of the cameras to cut down on mobile data)
I have managed to build a simple website with just one of the displays, but i want to be able to display all 8 of my cameras, IP addresses 192.168.0.157 - 165
My current code is
<html>
<head>
<script type="text/JavaScript">
var refreshInterval = 1000;
var url1 = "http://192.168.0.157/api/still?passwd=pass&"
var drawDate = true;
var img1;
function init() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
img = new Image();
img.onload = function() {
canvas.setAttribute("width", img.width)
canvas.setAttribute("height", img.height)
context.drawImage(this, 0, 0);
if(drawDate) {
var now = new Date();
var text = now.toLocaleDateString() + " " + now.toLocaleTimeString();
var maxWidth = 100;
var x = img.width-10-maxWidth;
var y = img.height-10;
context.strokeStyle = 'black';
context.lineWidth = 2;
context.strokeText(text, x, y, maxWidth);
context.fillStyle = 'white';
context.fillText(text, x, y, maxWidth);
}
};
refresh();
}
function refresh()
{
img.src = img.src = url1 + "t=" + new Date().getTime();
setTimeout("refresh()",refreshInterval);
}
</script>
<title>Test4</title>
</head>
<body onload="JavaScript:init();">
<canvas id="canvas"/>
</body>
</html>
Thanks in advance
I'm thinking make an array for every camera IP, and do all the API stuff for each of those.
var ip = [
"192.168.0.157",
"192.168.0.158",
"192.168.0.159",
"192.168.0.160",
"192.168.0.161",
"192.168.0.162",
"192.168.0.163",
"192.168.0.164",
"192.168.0.165"
];
var img = [];
function init() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
for (var i = 0; i < ip.length; i++) {
img[i] = new Image();
img[i].onload = (function() {
canvas.setAttribute("width", img[i].width);
canvas.setAttribute("height", img[i].height);
context.drawImage(this, 0, 0);
if (drawDate) {
var now = new Date();
var text = now.toLocaleDateString() + " " + now.toLocaleTimeString();
var maxWidth = 100;
var x = img[i].width - 10 - maxWidth;
var y = img[i].height - 10;
context.strokeStyle = 'black';
context.lineWidth = 2;
context.strokeText(text, x, y, maxWidth);
context.fillStyle = 'white';
context.fillText(text, x, y, maxWidth);
}
})();
}
refresh();
};
function refresh() {
for (var i = 0; i < img.length; i++) {
img[i].src = "http://" + ip[i] + "/api/still?passwd=pass&t=" + new Date().getTime();
}
setTimeout("refresh()",refreshInterval);
}

How do I create and draw an array of images on a canvas using Javascript?

I am trying the following code to allow me to create an image, allow custom values attached to it and draw in on an HTML canvas. It doesn't seem to be working though.
var canvas = document.getElementById('mainCanvas');
var context = canvas.getContext('2d');
function CreateObject(objectImage){
lastIndex++;
PlanObjects[lastIndex] = new PlanObject(lastIndex,currentSlide,24,24,24,24,objectImage);
context.drawImage(PlanObjects[lastIndex].img,PlanObjects[lastIndex].posX,PlanObjects[lastIndex].posY);
}
var PlanObjects = [];
var lastIndex = -1;
var currentSlide = 0;
function PlanObject(id, slide, width, height, posX, posY, img){
this.id = id;
this.slide = slide;
this.width = width;
this.height = height;
this.posX = posX;
this.posY = posY;
this.img = new Image(img);
}
CreateObject("imgs/icons_star.png");
HTML:
<div id="mainCanvasDiv"><canvas width="800" height="600" id="mainCanvas"></canvas>
I expect to create the object, store it in the array of PlanObjects (with it's customer values) and draw it onto the canvas but it doesn't seem to do that.
1) The input parameters for the image constructor are width and height. And you must separately set the source:
var myImage = new Image(100, 200);
myImage.src = 'picture.jpg';
document.body.appendChild(myImage);
[ https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image ]
2) Loading an image is asynchronous, so you need to handle the load event:
PlanObjects[lastIndex].img.addEventListener('load', function() {
context.drawImage(PlanObjects[lastIndex].img, PlanObjects[lastIndex].posX, PlanObjects[lastIndex].posY)
});
[ https://developer.mozilla.org/en-US/docs/Web/Events/load ]
[ https://jsfiddle.net/bvupyroc/ ]
I had to modify the new Image line to fix the problem
var canvas = document.getElementById('mainCanvas');
canvas.width = canvas.scrollWidth;
canvas.height = canvas.scrollHeight;
var context = canvas.getContext('2d');
function CreateObject(objectImage){
lastIndex++;
PlanObjects[lastIndex] = new PlanObject(lastIndex,currentSlide,24,24,24,24,objectImage);
context.drawImage(PlanObjects[lastIndex].img,PlanObjects[lastIndex].posX,PlanObjects[lastIndex].posY);
}
var PlanObjects = [];
var lastIndex = -1;
var currentSlide = 0;
function PlanObject(id, slide, width, height, posX, posY, img){
this.id = id;
this.slide = slide;
this.width = width;
this.height = height;
this.posX = posX;
this.posY = posY;
this.img = new Image();
this.img.src = img;
}
CreateObject("./imgs/icons_star.png");

Picture background for canvas particle

I'm trying to create background for every created particle.
Canvas pattern is not working properly. I'm getting this error >> "SyntaxError: An invalid or illegal string was specified"
HTML
<canvas id="canvas"></canvas>
JS
(function(){
window.onload = function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d'),
particles = {},
particleIndex = 0,
particleNum = 1;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.width);
function Particle(){
this.x = canvas.width / 2;
this.y = 0;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = 0.2;
particleIndex++;
particles[particleIndex] = this;
this.id = particleIndex;
this.test = 0;
this.maxLife = 100;
}
Particle.prototype.draw = function(){
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.test++;
if ( this.test >= this.maxLife ) {
delete particles[this.id];
};
var img = new Image();
img.src = 'img/aaa.png';
var pattern = ctx.createPattern(img,'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(this.x, this.y, 20, 20);
};
setInterval(function(){
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particleNum; i++) {
new Particle();
};
for(var i in particles) {
particles[i].draw();
}
},30)
}})();
I was trying to do this also with ctx.drawImage(), but picture was displayed one time only.
Any tips?:)
Fiddle
I think the issue is the image being loaded later than its used.
Inside your draw() you have:
var img = new Image();
img.src = 'img/aaa.png';
var pattern = ctx.createPattern(img,20,20);
It is a bad idea to create new images everytime you want to draw. I strongly suggest you create the img variable outside of the draw loop. Once you set the .src of an image, you have to wait until it is loaded to use it. There is an onload event you can use to let you know when its ready.
Here is an example:
var imgLoaded = false;
var img = new Image();
img.src = 'img/aaa.png';
img.onload = function() { imgLoaded = true; };
function draw() {
...
if (imgLoaded) {
var pattern = ctx.createPattern(img, 'repeat');
...
}
...
}

Javascript error in rails

i start to learn javascript with easy game tutorial http://www.youtube.com/watch?v=U7anheKJSaIand on RoR got error in index.html.erb:
<script>
var ctx, canvas;
var data;
window.onload = function main(){
canvas = document.createElement("canvas");
canvas.width = canvas.height = 200;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
init();
tick();
}
function init(){
data = new Tile(20,20);
}
function tick(){
window.requestAnimationFrame(tick);
update();
render();
}
function update(){}
function render(){
data.draw(ctx);
}
function Tile(x,y){
var x = x, y = y;
var tile = Tile.BlANK;
if(tile == null){
var _c = document.createElement("canvas");
_c.width = _c.height = 100;
_ctx = _c.getContext("2d");
_ctx.fillStyle = "skyblue";
//blank
_ctx.fillRect(0,0,100,100);
Tile.BlANK = new Image();
Tile.BLANK.src = _c.toDataURL();
tile = Tile.BLANK;
}
this.update = function(){}
this.draw = function(ctx){
ctx.drawImage(tile, x, y);
}
}
</script>
and this is error:
Tile.BLANK.src = _c.toDataURL();
Uncaught TypeError: Cannot set property src of undefined
Your error is here
Tile.BlANK = new Image();
It should be:
Tile.BLANK = new Image();
The error comes from .BlANK and it's because there is a typo. The l (L) is lowecase, and therefore later when you are trying to access the .src in you can't, because the real .BLANK is still undefined.
This is in function Tile(x,y){...}, but you also have the typo some other places. Just check your code for lowercase letters in .BLANK.

Categories

Resources