html5 canvas上下文.fillStyle无法正常工作 [英] html5 canvas context .fillStyle not working

查看:359
本文介绍了html5 canvas上下文.fillStyle无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是为了创作游戏而第一次给帆布做些尝试.我有图像显示,但奇怪的是fillStyle方法似乎不起作用. (至少画布背景在Google chrome中仍为白色.)

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. ( At least the canvas background is still white in google chrome.)

请注意,在我的代码中canvas var实际上是canvas元素2d上下文,也许那是让我感到困惑的地方?我看不到问题,如果有人可以,我将不胜感激.

Note that in my code the canvas var is actually the canvas elements 2d context, maybe that's where i'm getting myself confused? i can't see the problem, would appreciate if anyone else could.

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个注意事项:

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

  1. fillStyle does not cause your canvas to be filled. 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).

请等待直到图像实际加载,否则渲染可能会不一致或有错误.

Wait until your image actually loads, otherwise the rendering may be inconsistent or buggy.

注意画布中使用的跨域图像-大多数浏览器都会引发安全异常并停止执行您的代码.

Careful of cross-domain images used in your canvas - most browsers will throw a security exception and stop executing your code.

这篇关于html5 canvas上下文.fillStyle无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆