Javascript fillRect不从变量中绘制

时间:2014-09-19 14:36:10

标签: javascript canvas jsfiddle

为什么context.fillRect(10,10,20,20)填充一个矩形,但是当使用像player.x或player.y这样的变量时,它将不起作用?

如果我在JavaScript控制台中询问player.x的值,它会返回300.但是当在fillRect中使用player.x时,JavaScript会绘制一个空白。

var canvas = document.getElementById("canvas")
var context = canvas.getContext("2d")
var player = {}
player.x = 300
player.y = 80

window.addEventListener("load", function(){
    context.fillRect(10, 10, 20, 20) //works as intended
    context.fillRect(player.x, player.y, 20, 20) //does not work
});

http://jsfiddle.net/xy4h4obw/1/

1 个答案:

答案 0 :(得分:1)

如果你使画布足够宽,这可以正常工作:

http://jsfiddle.net/stmdet8c/

或者将player.x设置为较小的值