Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  87] [ 7]  / answers: 1 / hits: 15424  / 12 Years ago, sat, august 25, 2012, 12:00:00

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>

More From » html

 Answers
111

3 notes:




  1. 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).


  2. Wait until your image actually loads, otherwise the rendering may be inconsistent or buggy.


  3. Careful of cross-domain images used in your canvas - most browsers will throw a security exception and stop executing your code.



[#83435] Thursday, August 23, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylanalis

Total Points: 438
Total Questions: 85
Total Answers: 102

Location: Barbados
Member since Sun, Nov 27, 2022
1 Year ago
kylanalis questions
Sat, Oct 2, 21, 00:00, 3 Years ago
Tue, Oct 13, 20, 00:00, 4 Years ago
Thu, Feb 13, 20, 00:00, 4 Years ago
Tue, Jan 7, 20, 00:00, 4 Years ago
;