canvas drawImage error with JavaScript Class Attribute - javascript

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>

Related

Changing an image size

I can't figure out how to change the format of an image. I'm trying to make the Dino Game from Google Chrome. And changing the image size won't work.
My code:
window.onload = function() {
var cvs = document.getElementById("gameArea");
var ctx = cvs.getContext("2d");
var dino;
var obst = [];
function drawDino() {
var dinoImg = new Image();
dinoImg.src = 'dino.png';
dinoImg.onload = function() {
ctx.drawImage(dinoImg, 0, 0);
this.style.width = 100;
this.style.height = 100;
}
}
function drawObst() {
}
function draw() {
drawDino();
drawObst();
}
function startGame() {
setInterval(draw,50);
}
startGame();
}
Use the parameters of drawImage for resizing the image.
void ctx.drawImage(image, dx, dy, dWidth, dHeight);
window.onload = function() {
var cvs = document.getElementById("gameArea");
var ctx = cvs.getContext("2d");
var dino;
var obst = [];
function drawDino() {
var dinoImg = new Image();
dinoImg.src = 'http://lorempixel.com/400/200/'; //'dino.png';
dinoImg.onload = function() {
ctx.drawImage(dinoImg, 0, 0, 100, 100);
}
}
function drawObst() {
}
function draw() {
drawDino();
drawObst();
}
function startGame() {
setInterval(draw,1000);
}
startGame();
}
<canvas id="gameArea"></canvas>
I believe this is what you are looking for.
You did not pass width & height parameters to drawIamge
ctx.drawImage(dinoImg, x, y, width, height);
Read more at:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
window.onload = function() {
var cvs = document.getElementById("gameArea");
var ctx = cvs.getContext("2d");
var dino;
var obst = [];
function drawDino() {
var dinoImg = new Image();
dinoImg.src = 'https://i.imgur.com/HeGEEbu.jpg';
dinoImg.onload = function() {
//ctx.drawImage(dinoImg, 0, 0);
let width = 200;
let height = 200;
ctx.drawImage(dinoImg, 0, 0, width, height);
}
}
function drawObst() {
}
function draw() {
drawDino();
drawObst();
}
function startGame() {
setInterval(draw,50);
}
startGame();
}
#gameArea {
border:1px solid;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="gameArea" width="500" height="500"></canvas>
</body>
</html>

why are my sprites not drawing?

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>

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();
};

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

Why does the image not display?

Why does the image not display to the canvas in this example?
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
/*
var lockOrientation = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation;
screen.lockOrientation('landscape');
if (lockOrientation("landscape-primary")) {
screen.lockOrientation('landscape');
}
*/
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = 10;
var y = 10;
var width = 470;
var height = 310;
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, x, y, width, height);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
</script>
</head>
<body>
<canvas id="myCanvas" width="470" height="310" style="border:5px solid #123456;"></canvas>
</body>
</html>
You need to wait for the document to load before trying to select elements in the page.
Try wrapping your code like this:
window.onload = function() {
// your code goes here
};

Categories

Resources