html5 canvas context .fillStyle not working - javascript

Just giving canvas a go for the first time with the intention of creating a game. I have an image displaying but oddly the fillStyle method doesn't seem to be working. ( At least the canvas background is still white in google chrome.)
Note that in my code the canvas var is actually the canvas elements 2d context, maybe that's where i'm getting myself confused? i can't see the problem, would appreciate if anyone else could.
LD24.js:
const FPS = 30;
var canvasWidth = 0;
var canvasHeight = 0;
var xPos = 0;
var yPos = 0;
var smiley = new Image();
smiley.src = "http://javascript-tutorials.googlecode.com/files/jsplatformer1-smiley.jpg";
var canvas = null;
window.onload = init; //set init function to be called onload
function init(){
canvasWidth = document.getElementById('canvas').width;
canvasHeight = document.getElementById('canvas').height;
canvas = document.getElementById('canvas').getContext('2d');
setInterval(function(){
update();
draw();
}, 1000/FPS);
}
function update(){
}
function draw()
{
canvas.clearRect(0,0,canvasWidth,canvasHeight);
canvas.fillStyle = "#FFAA33"; //orange fill
canvas.drawImage(smiley, xPos, yPos);
}
LD24.html:
<html>
<head>
<script language="javascript" type="text/javascript" src="LD24.js"></script>
</head>
<body>
<canvas id="canvas" width="800" height="600">
<p> Your browser does not support the canvas element needed to play this game :(</p>
</canvas>
</body>
</html>

3 notes:
fillStyle does not cause your canvas to be filled. It means that when you fill a shape it will be filled with that color. Therefore you need to write canvas.fillRect( xPos, yPos, width, height).
Wait until your image actually loads, otherwise the rendering may be inconsistent or buggy.
Careful of cross-domain images used in your canvas - most browsers will throw a security exception and stop executing your code.

Wait till image loads as well:
var img = new Image();
img.onload = function() {
handleLoadedTexture(img);
};
img.src = "image.png";
function handleLoadedTexture(img) {
//call loop etc that uses image
};

Or maybe you were just missing
canvas.fill();
after
canvas.drawImage(smiley, xPos, yPos);

Related

How do I fix my html/javascript code to animate a sprite sheet?

I attempted to animate a sprite sheet using html and javascript to no avail. Here is my sprite sheet
Below is lines 36-59 of my code. I'm not getting any errors so I don't really know what's wrong. How do I fix/improve my code?
This is for a project I'm doing. I've tried using different methods I've found online but none really worked either. I've tried shifting the image as well.
<html>
<head>
<title>Tree Animation</title>
</head>
<body>
<canvas id='canvas'></canvas>
<script>
var canWidth = 400;
var canHeight = 100;
//position where the frame will be drawn
var x = 0;
var y = 0;
var srcX;
var srcY;
var sheetWidth = 230;
var sheetHeight = 79;
var frameCount = 5;
var width = sheetWidth/frameCount;
var height;
var currentFrame = 0;
var tree = new Image();
tree.src = "tree sprite.jpg"
var canvas = document.getElementById('canvas');
canvas.width = canWidth;
canvas.height = canHeight;
var ctx = canvas.getContext('2d');
function updateFrame(){
currentFrame = ++currentFrame%frameCount
srcX = currentFrame*width;
srcY = 0;
ctx.clearRect(x, y, width, height);
}
function draw(){
updateFrame();
}
setInterval(function(){
draw();
}, 100);
</script>
</body>
</html>
I expect the output to be an animation of a tree growing, but instead I'm getting a blank page.
you should provide more code or a snippet, there are several variables didn't show up in your code
and it's hard to debug your code if u use setInterval, you should make sure your code can work first.
maybe you can try step by step:
draw the whole img on the canvas first. if it works, go next
invoke your draw() function manually, check if the img drawed
invoke more, such assetTimout(draw, 1000), check the result
ok, and i think you can console.log these variables in draw

Canvas wont display image inside of it

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id="spriteCanvas" width="500" height="500">
<img id="coin" width="440" height="40" src="coin.png">
</canvas>
</body>
</html>
I tried placing an image inside a canvas element, but it won't display on the browser. I know the image tag works because it's displayed if I place it outside of the canvas element. Also, if I inspect the canvas element, I can see that the image is inside, but its dimensions are 0 by 0. Can somebody explain why this isn't working?
EDIT: My original code added the image through javascript, but it wouldn't show on the canvas. It was giving me the same problems as above. But I just realized I was missing "onload".
original code:
var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');
function Sprite(canvas, width, height, image){
this.context = canvas.getContext("2d");
this.width = width;
this.height = height;
this.image = image;
}
Sprite.prototype.render = function() {
var that = this;
this.context.drawImage(that.image, 0, 0);
}
function init() {
var coin = new Sprite(sCanvas, 100, 100, coinImage);
coin.render();
}
init();
editted code:
var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');
function Sprite(canvas, width, height, image){
this.context = canvas.getContext("2d");
this.width = width;
this.height = height;
this.image = image;
}
Sprite.prototype.render = function() {
var that = this;
this.context.drawImage(that.image, 0, 0);
}
coinImage.onload = function () {
var coin = new Sprite(sCanvas, 100, 100, coinImage);
coin.render();
}
This isn't how a <canvas> tag works. If you want your image to appear in your canvas, you will have to use JavaScript to place the pixels of the image into your canvas.
<canvas>s are exactly what they state: canvases. They are an element for you to draw on programmatically. If you just want to display an image on a page, you don't need a canvas, you just need the <img> tag. In fact, elements should not be placed in <canvas>.
Take a look at CanvasRenderingContext2D.drawImage() and this tutorial: HTML5 Canvas Image Tutorial.
And this snippet:
var canvas = document.getElementById("painting"),
ctx = canvas.getContext("2d"),
image = new Image();
image.onload = function() {
ctx.drawImage(image, 30, 50);
};
image.src = "http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.png?v=10a9e8743fb0";
<canvas id="painting" width="300" height="300"></canvas>
To draw an image on a canvas, use the following method:
drawImage(image,x,y)
If the image you want to draw is not in the DOM already you can load an image directly from a URL with a few lines of javascript.
function loadAndDrawImage(url)
{
// Create an image object. This is not attached to the DOM and is not part of the page.
var image = new Image();
// When the image has loaded, draw it to the canvas
image.onload = function()
{
// draw image...
}
// Now set the source of the image that we want to load
image.src = url;
}
loadAndDrawImage("http://www---.png");

Html5 canvas animation. How to reset rectangle when it hits the end

Hey Im experimenting with some html5 animation and so far I have a square that "falls" whenever I press the button. I was wondering how i could have it go back to the top when it hits the bottom and fall again.
My current code is:
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="200" height="400" style="border:1px solid black;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
function draw (x,y){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.save();
var side = 10
var up = 10
ctx.clearRect(0,0,200,400);
ctx.fillStyle = "#FF0000";
ctx.fillRect(x,y,up,side);
ctx.restore();
y += 5;
var loopTimer = setTimeout('draw('+x+','+y+')',30);
}
</script>
<button onclick="draw(0,0)">draw</button>
</body>
</html>
Using your variables y, you can simply check if it is below the height of the canvas height.
if( y > c.height ){ // use the canvas height, not the context height
y = 0;
}
Also, the way you're currently calling the timer is a bit inefficient. Instead of :
var loopTimer = setTimeout('draw('+x+','+y+')',30);
I would recommend
var loopTimer = setTimeout(function(){ draw(x,y); },30);
Here's a working example: http://jsfiddle.net/vwcdpLvv/

Drawing an image on the canvas in HTML5

I have been trying to get an image drawn on the canvas however have failed to do so. The HTML code simply creates the canvas element "canvas1" with no additional processing.
Here is the JS:
function loadlogo(){
var logo = new Image();
var canvas = document.getElementById('canvas1');
var context = canvas.getContext('2d');
//resize the canvas to the current window
context.canvas.width = window.innerWidth;
context.canvas.height = window.innerHeight / 3;
logo.src = "images/1.png";
logo.onload = function() {context.drawImage(logo,0,0;};
context.shadowOffsetX = 50;
context.shadowOffsetY = 30;
context.shadowColor = "pink";
}
window.addEventListener("load",loadlogo,false);
window.addEventListener("resize",loadlogo,false);
Any help you could give would be awesome!!!
I have tried this many ways and am stuck.
Thanks,
Bryan
Put your onload function for img before you assign img src
Change this part
{context.drawImage(logo,0,0;};
^ Notice the missing end-parenthesis here
to
{context.drawImage(logo,0,0)};
I would as QBM5 also recommend to put the src after setting onload to be sure it's properly initialized.

HTML5/JavaScript based game - Controlling x/y coordinates with touch

I am trying to make a HTML5 Canvas/JavaScript game. I watched some tutorials, and I understand what everying is meant for, but I don't get the right controls for touch devices.
I want to get my 'airship', where my finger touches the screen. It is not only working with where my mouse is positioned.
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<script type="text/javascript">
window.onload = function() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var canvasWidth = canvas.offsetWidth;
var canvasHeight = canvas.offsetHeight;
var bg1 = new Image();
var bg2 = new Image();
bg1.src = "img/spritesheet.png";
bg2.src = "img/spritesheet.png";
var increment = -5;
var sYbg1 = 0;
var sYbg2 = 960;
var ship = new Image();
ship.src = "img/spritesheet.png";
var mouseX;
var mouseY;
canvas.onmousemove = function() {
mouseX = window.event.clientX - canvas.offsetLeft; // mousePositionX
inside the <canvas> element
mouseY = window.event.clientY - canvas.offsetTop; // mousePositionY
inside the <canvas> element
};
var animate = function() {
context.clearRect(0,0,canvasWidth,canvasHeight);
context.drawImage(bg1,0,sYbg1,canvasWidth,canvasHeight,0,0,canvasWidth,canvasHeight);
context.drawImage(bg2,0,sYbg2,canvasWidth,canvasHeight,0,0,canvasWidth,canvasHeight);
sYbg1 += increment;
sYbg2 += increment;
if(sYbg2 <= 0) {
sYbg1 = 0;
sYbg2 = 960;
}
context.drawImage(ship,320,0,65,105,(mouseX-32),(mouseY-52),65,105);
setTimeout(animate,25);
};
animate();
}
</script>
</head>
<body>
<canvas id="canvas" width="320" height="480"></canvas>
</body>
</html>
(!MY CODE IS ONLY WORKING IN CHROME!) --> But thats not important not, I know about the window.event and that it's not working in FF.
I hope someone can explain to me what I need to do. I tried to fix my problem to use onmousemove and onmousedown together, but that wasn't working for me too. Thanks a lot for the help!
I will provide a hint, in case you haven't gotten there yet, and for future researchers. You have a mouse event handler (mousemove). I don't see a touch event handler. There are some options depending on your browser, which is unclear to me which you want to use...
However you can start looking at https://developers.google.com/ or MDN https://developer.mozilla.org/en-US/ as good starting points.

Categories

Resources