HTML5画布上下文.fillStyle不起作用

4

我第一次尝试使用Canvas创建游戏。我已经显示了一张图片,但是fillStyle方法似乎不起作用(至少在Google Chrome中画布背景仍然是白色的)。

请注意,在我的代码中,canvas变量实际上是canvas元素的2D上下文,也许这就是让我感到困惑的地方?我看不出问题所在,如果有人能帮忙解答就太好了。

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>
3个回答

4

注意事项:

  1. fillStyle 不会导致你的画布被填充。它意味着当你 填充 一个 形状 时,它将被填充为该颜色。因此,你需要编写 canvas.fillRect(xPos, yPos, width, height)

  2. 等待图像实际加载完成后再进行渲染,否则渲染可能不一致或出现错误。

  3. 小心使用跨域图像在你的画布中 - 大多数浏览器会抛出安全异常并停止执行你的代码。


都,我真不敢相信我错过了那个,谢谢!如何检查图像是否已加载?是的,我很快就会使用自己的图像。 - Holly
请注意,.fillRect() 方法是画布的2D上下文的方法,而不是画布本身,这个答案中可能(无意中)提到了它! - Tim S.
@TimS。我只是根据问题中的变量名来进行了跟随。我能理解这可能会让人感到困惑。 - Jakub Hampl

1

等待图片加载完成:

var img = new Image();
img.onload = function() {
    handleLoadedTexture(img);
};
img.src = "image.png";

function handleLoadedTexture(img) {
    //call loop etc that uses image
};

1
我发现了Chrome中fillStyle和fillRect()存在问题。如果我指定ctx.fillStyle="rgba(0,0,0,0)",实际上得到的是fillStyle为rgba(0,0,0,1)。这导致了后续渲染依赖于画布被填充为透明黑色的出现混乱。这是一个已知的Chrome bug,还是我发现了新问题? - David Edwards

0

或许你只是错过了

canvas.fill();

之后

canvas.drawImage(smiley, xPos, yPos);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接