画布中的图像宽度未正确显示

时间:2014-07-12 14:19:48

标签: javascript html html5-canvas

我有这个画布我正在画画。我想让图像放在左下角。

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

但问题是当我使用变量player1Y时,它会导致图像显示在坐标(0,canvasHeight)上。实际上,它会导致图像无法显示。但是当我写canvas.drawImage(image, player1X, canvasHeight - image.height)时它完美无缺。

如何使变量控制图像的位置?

这是JSfiddle:http://jsfiddle.net/u9Ehs/10/

1 个答案:

答案 0 :(得分:0)

问题是当您设置imageHeight& amp;图像时图像尚未完全加载。 player1Y。

重构代码以在image.onload中设置所有与图像相关的变量:

示例代码和演示: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>