【发布时间】:2018-01-13 18:15:46
【问题描述】:
我在用 java 和 c++ 编码后开始学习 javascript,我正在尝试绘制一个矩形。如果我只是在正文中的脚本中正常编码,但我想让我的文件看起来整洁并且有一个函数,我可以在我的程序中调用更多的矩形。我已经用谷歌搜索了,但我仍然无法弄清楚如何做到这一点。
我尝试将函数放在 head 部分和我的 js 文件中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PacMan</title>
<script scr="pac.js"></script>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//function drawRect(ctx, startX, startY, width, height, color){
//ctx.beginPath();
// ctx.rect(startX,startY,width,height);
// ctx.fillStyle = color;
// ctx.closePath();
// }
</script>
</head>
<body>
<canvas id="canvas" width="1000" height="720"></canvas>
<script>
drawRect(ctx,10,10,10,10, "#FF0000");
// this works but i can not get the function to work
//var canvas = document.getElementById("canvas");
//var ctx = canvas.getContext("2d");
//ctx.beginPath();
// ctx.rect(900, 10, 50, 50);
// ctx.fillStyle = "#FF0000";
//ctx.fill();
// ctx.closePath();
</script>
</body>
</html>
这是我创建的 .js 文件,试图让我的函数保持井井有条,这样它们就不会弄乱我的文件
function drawRect(ctx,h1,h2,w1,w2, color){
//i tired at one point putting this into function
//var canvas = document.getElementById("myCanvas");
// var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(20, 40, 50, 50);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
【问题讨论】:
标签: javascript html draw