【问题标题】:html5 canvas context .fillStyle not workinghtml5画布上下文.fillStyle不起作用
【发布时间】:2022-04-09 18:30:35
【问题描述】:

第一次尝试使用画布是为了创建一个游戏。我有一个图像显示,但奇怪的是 fillStyle 方法似乎没有工作。 (至少在谷歌浏览器中画布背景仍然是白色的。)

请注意,在我的代码中,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>

【问题讨论】:

    标签: javascript html html5-canvas


    【解决方案1】:

    3 个注释:

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

    2. 等到您的图片实际加载完毕,否则渲染可能会不一致或有错误。

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

    【讨论】:

    • 真不敢相信我错过了谢谢!如何检查图像是否已加载?是的,我一定会尽快使用我自己的图片。
    • 请注意,.fillRect() 方法是画布的 2D 上下文的方法,而不是这个答案中提到的(可能是偶然的)画布本身!
    • @TimS。我只是按照问题中的变量名。我知道这可能会令人困惑。
    【解决方案2】:

    等待图片加载:

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

    【讨论】:

    • 我在 Chrome 中发现了 fillStyle 和 fillRect() 的问题。如果我指定 ctx.fillStyle="rgba(0,0,0,0)",我最终得到的是 rgba(0,0,0,1) 的填充样式。这导致随后的渲染,依赖于用透明黑色填充的画布,变得乱七八糟。这是一个已知的 Chrome 错误,还是我发现了新的东西?
    【解决方案3】:

    也许你只是失踪了

    canvas.fill();
    

    之后

    canvas.drawImage(smiley, xPos, yPos);
    

    【讨论】:

      最近更新 更多