我希望在 Firefox 的 Canvas 上绘制一个 320 X 240 像素的蓝色大矩形,但我得到的是一个黑色矩形。我实际上只是为了实验而绘制像素,但由于某种原因,这无法正常工作。代码中的所有内容在 JavaScript 绘制函数中似乎都有意义,但这是不可行的?任何想法,这是代码,
<html>
<head>
<title>Canvas</title>
<script type="text/javascript">
function draw()
{
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");
var red = 0;
var green = 0;
var blue = 255;
ctx.fillStyle = "rgb( red, green, blue)";
for(var i = 0; i < 320; i++)
{
for(var j = 0; j < 240; j++)
{
ctx.fillRect (i , j , 1, 1);
}
}
}
}
</script>
<style type="text/css">
body
{
margin: 50px 50px;
}
canvas
{
border: 1px solid black;
}
#container
{
position: relative;
width: 640px;
height: 480px;
margin: 0 auto;
}
</style>
</head>
<body onload="draw();">
<div id = "container">
<canvas id="canvas" width="640px" height="480px"></canvas>
</div>
</body>
</html>
最佳答案
您需要使用..." + variable + "...
让字符串使用变量的值。事实上你正在路过rgb( red, green, blue)
作为 fillStyle,它默认为黑色,因为它无效
ctx.fillStyle = "rgb("+red+","+green+","+blue+")";
关于javascript - 使用 HTML 5 Canvas 矩形(像素大小)绘图会得到黑色矩形而不是蓝色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21542787/