我正在尝试在 Canvas 下方创建。
我的代码如下。但我无法使 Canvas 看起来像上面的屏幕截图。那么有人可以帮助我吗?
谢谢
<html>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
var canvas;
var canvasContext;
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
canvasContext.fillStyle = 'blue';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(355,350,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(190,350,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(520,350,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(355,200,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(190,200,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(520,200,120,90);
}
</script>
</html>
最佳答案
.fillRect
创建一个填充颜色的区域。但是,.rect
创建一个“形状”,然后您可以在其上使用 .fill()
和 .Stroke()
方法。
在下面的示例中,为了简洁起见,将创建转换为循环
var canvas;
var canvasContext;
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
canvasContext.fillStyle = 'blue';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
var height = 90;
var width = 120;
var leftOffset = 190;
var topOffset = 200;
for(var x = 0; x < 6; x++){
canvasContext.beginPath();
canvasContext.rect(leftOffset,topOffset,width,height);
canvasContext.fillStyle = 'grey';
canvasContext.fill();
canvasContext.lineWidth = 4;
canvasContext.strokeStyle = 'lightblue';
canvasContext.stroke();
leftOffset += 165;
if(x === 2){
leftOffset = 190;
topOffset = 350;
}
}
}
<强> JSFIDDLE
这个tutorial在 HTML5 Canvas 矩形上非常方便
<小时/>要添加文本,您需要在 rect
创建循环之后(或之前)附加以下内容
canvasContext.beginPath();
canvasContext.font = '20pt Arial';
canvasContext.textAlign = 'center';
canvasContext.fillStyle = 'white';
canvasContext.shadowColor = 'black';
canvasContext.shadowOffsetX = 4;
canvasContext.shadowOffsetY = 4;
canvasContext.fillText('CHOOSE A SCENE TO COLOR', canvas.width/2,55);
<强> UPDATED FIDDLE
text align 的教程, text shadow ,和 text .
关于javascript - 如何为边框框创建 html5 Canvas ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41627492/