yamahamm yamahamm - 5 months ago 9
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();
image.src="you.png";

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

canvas.rect(0, 0, canvasWidth, canvasHeight);
canvas.fillStyle="#5c7792";
canvas.fill();

$(image).load(function(){
canvas.drawImage(image, player1X , player1Y);
});


but the problem is that when I use variable
player1Y
, 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/

Answer

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>
<html>
<head>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
window.onload = function() {

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

    var player1X=0;
    var player1Y;

    var img=new Image();
    img.onload=start;
    img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/ship.png";
    function start(){
        player1Y=canvas.height-img.height;  
        ctx.drawImage(img,player1X,player1Y);
    }


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