我正在学习JavaScript和HTML 5.
我根本无法在画布周围找到简单的边框。 html完全忽略了CSS。
这是我的代码:
JavaScript的:
function buildCanvas()
{
var w = window.innerWidth / 2;
var h = window.innerHeight / 2;
document.write("<CANVAS WIDTH=" + w + " HEIGHT=" + h + " ID=canvas_1>");
document.write("</CANVAS>");
drawOnCanvas();
}
function drawOnCanvas()
{
var canvas = document.getElementById("canvas_1");
if (canvas.getContext)
{
var canvas_context = canvas.getContext("2d");
canvas_context.font = "84px Ariel";
canvas_context.fillText("Test", 500, 300);
}
}
HTML:
<!DOCTYPE HTML>
<HTML>
<HEAD>
<LINK rel="stylesheet" type="text/css" href="css/style.css">
<TITLE>Canvas Test</TITLE>
<SCRIPT LANGUAGE="JavaScript" SRC="scripts/external.js"></SCRIPT>
</HEAD>
<BODY onLoad="buildCanvas()">
</BODY>
</HTML>
样式表:
canvas
{
border: 1px solid black;
}
答案 0 :(得分:5)
在文档加载后(即document.write
事件期间),您正在调用onload
。这将使用包含新内容的新文档替换当前文档。简而言之,它会破坏页面,包括样式定义。
请改为尝试:
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
canvas.id = "canvas_1";
document.body.appendChild(canvas);