简体   繁体   English

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

[英]html5 canvas context .fillStyle not working

Just giving canvas a go for the first time with the intention of creating a game. 只是为了创造一个游戏,第一次给画布一个去。 I have an image displaying but oddly the fillStyle method doesn't seem to be working. 我有一个图像显示但奇怪的是fillStyle方法似乎没有工作。 ( At least the canvas background is still white in google chrome.) (至少画布背景在谷歌浏览器中仍为白色。)

Note that in my code the canvas var is actually the canvas elements 2d context, maybe that's where i'm getting myself confused? 请注意,在我的代码中,canvas var实际上是canvas元素2d上下文,也许这就是我让自己感到困惑的地方? i can't see the problem, would appreciate if anyone else could. 我看不出问题,如果有其他人可以,我会很感激。

LD24.js: 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: 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 notes: 3笔记:

  1. fillStyle does not cause your canvas to be filled. fillStyle不会导致您的画布被填充。 It means that when you fill a shape it will be filled with that color. 这意味着当你填充一个形状时 ,它将填充该颜色。 Therefore you need to write canvas.fillRect( xPos, yPos, width, height) . 因此,您需要编写canvas.fillRect( xPos, yPos, width, height)

  2. Wait until your image actually loads, otherwise the rendering may be inconsistent or buggy. 等到图像实际加载,否则渲染可能不一致或有问题。

  3. Careful of cross-domain images used in your canvas - most browsers will throw a security exception and stop executing your code. 仔细考虑画布中使用的跨域图像 - 大多数浏览器都会抛出安全异常并停止执行代码。

Wait till image loads as well: 等到图像加载:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM