why are my sprites not drawing? - javascript

I am learning how to make a minigame with javascript, but my player is not rendered.
I don´t know why. I am not getting any errors.
The startGame() starts with
How should I edit my code to get it to run and get the sprites to render?
Here's my code :
<html>
<head>
<meta name="viewport" content="width = device-width, initial-scale = 1.0"/>
</head>
<body onload='startGame()'>
<script>
function startGame() {
createCanvas.start();
}
let ninja = new Image();
let ninjaImage = "images/player/stand01.png"
const createCanvas = {
canvas : document.createElement('canvas'),
start() {
this.canvas.width = 600;
this.canvas.height = 400;
this.context = this.canvas.getContext('2d');
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
}
}
function sprite(options){
let that = {};
that.context = options.context;
that.width = options.width;
that.height = options.height;
that.image = options.image;
return that;
that.render = function () {
that.context.drawImage(
that.image, 0, 0, that.width, that.height, 0, 0, that.width, that.height);
}
player.render();
}
player = sprite ({
width: 100,
height: 100,
image: ninjaImage
});
</script>
</body>
<style>
canvas {
border: 1px solid black;
background: grey;
}
</style>

Assuming you have taken care of the early return, your code isn't working because you are likely because your render() function is being called when your player object is created. Before you can draw anything it's better to setup your canvas and context object first.
My recommendation for creating objects in a class like way is to use the function/prototype approach.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
display: block;
margin: auto;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
void function() {
"use strict";
/*
In JS a 'class' is made up of two things
A constructor function that attaches individual properties to every new instance
(When a contructor is called with 'new' I.E. 'new Sprite()', the 'this' variable in the constructor
is assigned to the newly created object.
The other part is a prototype that holds shared properties between instances of
the 'class'. (in an instance prototype values are accessible via the this keyword).
*/
// Constructor function
function Sprite(x,y,width,height,image) {
this.x = x || 0.0;
this.y = y || 0.0;
this.width = width || 1.0;
this.height = height || 1.0;
this.image = image || null;
}
// Prototype object (Shared between instances)
Sprite.prototype = {
render: function(ctx) {
if (this.image) {
ctx.drawImage(this.image,this.x,this.y,this.width,this.height);
} else {
ctx.fillStyle = "darkred";
ctx.fillRect(this.x,this.y,this.width,this.height);
}
}
};
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var sprite = null;
var image = new Image();
image.src = "https://i.stack.imgur.com/WnNgY.png";
// window.onload, called when page has loaded
onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
ctx.fillStyle = "gray";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
sprite = new Sprite(65,55,50,50,image);
sprite.render(ctx);
}
}();
</script>
</body>
</html>

Related

Creating a square with mousedown

I want a red square to appear where I click on the canvas with my mouse, but I'm having trouble getting the square to appear on the canvas when I click on it. The function start contains window.addEventListener() which is supposed to be creating a component on the mouseclick, but I'm not sure if I am missing something or if I'm just completely wrong.
<!DOCTYPE html>
<html>
<head>
<meta = name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="start() {
gameArea.start();
}
var gameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 840;
this.canvas.height = 540;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
//I don't know what Im doing wrong here
window.addEventListener('mousedown', function (e) {
new component(30, 30, "red", 10, 120);
})
}
}
//and here
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
}
</script>
</html>
window.addEventListener('mousedown', (e) => {
const {layerX, layerY} = e;
const rectSize = 30;
this.context.fillStyle = 'red';
this.context.fillRect(layerX - rectSize / 2, layerY - rectSize / 2, rectSize, rectSize);
});
you passed a function () {} which had no context of your gameArea. The other part is a canvas api.

Context2D is undefined after it was defined

I have a simple javascript constructor-function which constructs an object that is supposed to draw conways game of life:
function startGame() {
var myGameOfLife = new GameOfLife();
myGameOfLife.initialize(500, 500);
}
function GameOfLife() {
this.canvas = document.createElement("canvas");
this.initialize = function(width, height) {
this.canvas.width = width;
this.canvas.height = height;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(this.update, 20);
}
this.update = function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
</script>
</body>
</html>
When i debug this script, i can see that in the initialize-function this.context gets assigned. But when the update-function is called by the interval, this.context is undefined.
Why is it undefined when i can clearly see it being defined before?
you're referring to the wrong this in the update function.
Just bind the right context (that is the context of GameOfLife constructor)
this.interval = setInterval(this.update.bind(this), 20);
or alternatively use an arrow function in order to let it inherit the outer scope.
this.update = () => {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}

Repeated image in canvas?

I'm trying to make an image repeat, but the image is not appearing at all? I'm not sure what I have done wrong or how to fix this. I was wondering if anyone could help?
<head>
<style type="text/css">
canvas {
background: black;
}​
html, body, div, canvas {
margin: 0;
padding: 0;
}
html, body {
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="my_canvas"></canvas>
<script src="/js/all.js"></script>
</body>
JS:
var canvas = null;
var context = null;
setup = function() {
canvas = document.getElementById("my_canvas");
context = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var image = new Image();
image.src = 'http://example.com/tile.png';
var pat = context.createPattern(img, "repeat"); // repeat the image as a pattern
context.fillStyle = pat;
context.rect(0,0,150,100);
context.fill();
};
setup();
You need to wait for the image to load before painting it on the canvas
var image = new Image();
image.src = 'http://example.com/tile.png';
image.onload = function() {
var pat = context.createPattern(img, "repeat"); // repeat the image as a pattern
context.fillStyle = pat;
context.rect(0,0,150,100);
context.fill();
};

canvas drawImage error with JavaScript Class Attribute

I am trying to use class on drawImage function.
But it seems that drawImage function couldn't get the attribute img of variable monster.
I have no idea what would caused this error.
Not quite understand why browser give me the below error code ... please help me.
Uncaught TypeError: Cannot read property 'img' of undefined.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tower Defense</title>
<style>
canvas {
padding: 0;
margin: auto;
display: block;
}
</style>
</head>
<body>
<script>
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
function Monster(img, x = 0, y = 0, w,h) {
this.img = img;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
var monster;
var DrawMonster = function(mons) {
ctx.drawImage(mons.img, mons.x, mons.y, mons.w, mons.h);
}
var PreLoadImages = function() {
var img = new Image();
img.addEventListener("load", function() { // or img.onload = function() { ...
monster = new Monster(this, 0, 0, 100, 100);
});
img.src = "res/Mons_Pirate.jpg";
}
PreLoadImages();
DrawMonster(monster);
</script>
</body>
</html>
Please change the link (res/Mons_Pirate.jpg) of image while testing.
DrawImage should be inside the image load function.Instance of Monster is created only inside the Image load function.Image will be loaded in async.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tower Defense</title>
<style>
canvas {
padding: 0;
margin: auto;
display: block;
}
</style>
</head>
<body>
<script>
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
function Monster(img, x = 0, y = 0, w,h) {
this.img = img;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
var monster;
var DrawMonster = function(mons) {
ctx.drawImage(mons.img, mons.x, mons.y, mons.w, mons.h);
}
var PreLoadImages = function() {
var img = new Image();
img.addEventListener("load", function() { // or img.onload =
function() {
monster = new Monster(this, 0, 0, 100, 100);
DrawMonster(monster);
});
img.src = "res/Mons_Pirate.jpg";
}
PreLoadImages();
</script>
</body>
</html>

Image not showing in javascript

When running my program I have an image I want to draw on the mouse's x position(clientX) and y position(clientY).
When running the program regularly by not using client x and y in the position for being drawn, it works just fine.
This is the image
//variables
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var player = new Image();
player.src = "http://i.stack.imgur.com/P9vJm.png";
//functions
function start() {
setInterval(update, 10);
}
function update() {
clearRender();
render();
}
function clearRender() {
ctx.clearRect(0,0,1300,500);
}
function render() {
var mx = document.clientX;
var my = document.clientY;
ctx.drawImage(player, mx, my);
}
#canvas {
height: 500px;
width: 1300px;
background-color: black;
position: absolute;
left: 25px;
top: 50px;
}
body {
background-color: white;
}
<!DOCTYPE html>
<html>
<head>
<title> Space Invaders </title>
<link rel="stylesheet" type="text/css" href="invader.css">
</head>
<body>
<canvas id="canvas"> </canvas>
<script type="text/javascript" src="invader.js"></script>
</body>
</html>
To get you started, you would need an event handler to get your mouse position
c.addEventListener('mousemove', update, false);
JS:
//variables
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var player = new Image();
player.src = "http://i.stack.imgur.com/P9vJm.png";
c.addEventListener('mousemove', update, false);
//functions
function start() {
setInterval(update, 10);
}
function update(e) {
//clearRender();
render(e);
}
function clearRender() {
ctx.clearRect(0, 0, 1300, 500);
}
function render(e) {
var pos = getMousePos(c, e);
posx = pos.x;
posy = pos.y;
ctx.drawImage(player, posx, posy);
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
Here's a fiddle: https://jsfiddle.net/vwbo8k6k/
This might help you understand more about mouse positions, but I hope the image shows this time.
http://stackoverflow.com/a/17130415/2036808

Categories

Resources