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

html5 canvas context .fillStyle not working

本文关键字:fillStyle 不起作用 上下文 html5      更新时间:2023-09-26

只是第一次尝试canvas,目的是创建一个游戏。我有一个图像显示,但奇怪的是,fillStyle方法似乎不起作用。(至少画布背景在谷歌chrome中仍然是白色的。)

请注意,在我的代码中,canvas var实际上是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条注释:

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

  2. 等待图像实际加载,否则渲染可能不一致或有问题。

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

等待图像加载:

var img = new Image();
img.onload = function() {
    handleLoadedTexture(img);
};
img.src = "image.png";
function handleLoadedTexture(img) {
    //call loop etc that uses image
};

或者您可能只是缺少

canvas.fill();

之后

canvas.drawImage(smiley, xPos, yPos);