[英]html5 canvas context .fillStyle not working
只是為了創造一個游戲,第一次給畫布一個去。 我有一個圖像顯示但奇怪的是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>
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
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.