简体   繁体   English

为什么我的画布不画画?

[英]Why won't my canvas draw?

My canvas element isnt working right. 我的画布元素无法正常工作。 It wont draw a rectangle. 它不会画一个矩形。 Please help me diagnose the problem. 请帮助我诊断问题。 I don't know where the problem is, is it my css, javascript, or html? 我不知道问题出在哪里,是我的CSS,JavaScript还是HTML? Did I set up everything right because I got no errors when i ran my debugger and put it on a server? 我是否设置正确了一切,因为在运行调试器并将其放在服务器上时没有错误?

index.html index.html

<!DOCTYPE html>
<html>
<head>
<title>Paco Developement</title>
<link rel="stylesheet" href="style.css" />
<script src="game.js"></script>
</head>
<body>
<canvas id="canvasBg" height="500" width="800"></canvas>
<canvas id="character" height="500" width="800"></canvas>
</body>
</html>

style.css style.css

* {
padding:0px;
margin:0px;
}

header, section, footer, aside, nav, article, figure, hgroup{
    display:block;
}

body {
background:#BADA55;
width:100%;
height:100%;
}

#canvasBg {
display:block;
background:#fff;
margin:100px auto 0px;
}

#character {
display:block;
margin:-500px auto 0px;
}

game.js game.js

var canvasBg = document.getElementById('canvasBg');
var bgCtx = canvasBg.getContext("2d");

document.addEventListener('load',drawRect,false);

function drawRect(){
bgCtx.fillStyle="#FF0000";
bgCtx.fillRect(0,0,150,75);
}

Live Demo 现场演示

Change document to window for your event listener and it should work for you. document更改为事件侦听器的window ,它应该对您有用。

window.addEventListener('load',drawRect,false);

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

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