html5画布上下文.fillStyle不起作用
html5 canvas context .fillStyle not working
只是第一次尝试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条注释:
-
fillStyle
不会导致画布被填充。这意味着当填充一个形状时,它将填充该颜色。因此,您需要编写canvas.fillRect( xPos, yPos, width, height)
。 -
等待图像实际加载,否则渲染可能不一致或有问题。
-
小心画布中使用的跨域图像-大多数浏览器都会抛出安全异常并停止执行代码。
等待图像加载:
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);
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 监视函数从服务返回不起作用,但作用域函数起作用
- 幻灯片滚动javascript不起作用
- 简单的javascript在Shopify中不起作用
- Recaptcha在IE7和IE8中不起作用
- Ember Data DS.Model's set函数不起作用
- JsFiddle上的鼠标事件不起作用
- 我的AngularJS表达式没有'不起作用
- 点击按钮输入不起作用
- 面向对象的Javascript代码在IE7中不起作用
- 分部隐藏在jquery中不起作用
- 在phonegap应用程序内部重定向不起作用
- Array.length似乎不起作用;console.log则显示其他情况
- $ionicplatform内的$scope不;不起作用
- 我的javascript for循环不起作用
- Meteor-添加用户自定义字段的方法不起作用
- 为什么 .focus() 不起作用,而 .css(“color”,“red”) 在同一个选择器上起作用
- Textarea必需的attribut在javascript中不起作用
- html5画布上下文.fillStyle不起作用
- .fillStyle 不起作用,控制台中没有错误