yamahamm yamahamm - 6 months ago 15
HTML Question

Image width in canvas isnt being displayed correctly

I have this canvas I'm drawing onto. And I want to make image to be placed in the left lower corner.

var canvasWidth = 800;
var canvasHeight = 600;

$("#gameCanvas").attr("width", canvasWidth);
$("#gameCanvas").attr("height", canvasHeight);

var canvas = $("#gameCanvas")[0].getContext("2d");

var image = new Image();

var player1X =0;
var imageHeight=image.height;
var player1Y = canvasHeight - imageHeight;

canvas.rect(0, 0, canvasWidth, canvasHeight);

canvas.drawImage(image, player1X , player1Y);

but the problem is that when I use variable
, it results in image being displayed at coordinates (0, canvasHeight). Actually, it results in image not being shown. But when I write
canvas.drawImage(image, player1X, canvasHeight - image.height)
it works perfectly.

How do I make the variable to control the posiotion of image?

Here is JSfiddle: http://jsfiddle.net/u9Ehs/10/


The problem is that the image hasn't fully loaded when you are setting imageHeight & player1Y.

Refactor your code to set all image related variables inside image.onload:

Example code and a Demo: http://jsfiddle.net/m1erickson/CSQGh/

enter image description here

<!doctype html>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
window.onload = function() {

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var player1X=0;
    var player1Y;

    var img=new Image();
    function start(){

}; // end $(function(){});
    <canvas id="canvas" width=300 height=300></canvas>