想要创建交互式HTML5游戏之前,让我们先从最基本的开始。
首先,单击“Red Square,如果您没有看到一个画布红场你problably想要正确的web浏览器继续。
<canvas id="c1" width="200" height="200" style="border:solid 1px #000000;"></canvas>
<button οnclick="draw_square();return true;">Red Square</button> <script>
function draw_square() {
var c1 = document.getElementById("c1");
var c1_context = c1.getContext("2d");
c1_context.fillStyle = "#f00";
c1_context.fillRect(50, 50, 100, 100);
}
</script>
画在canvas上的任何东西,你不要把任何开始标记和结束标记之间的<canvas>,浏览器支持画布就忽略它。你只能使用Javascript来绘画。
第一条规则,你的canvas元素必须有一个ID,因此我们可以使用Javascript来定位它。其次,每一个canvas都有我们所说的“上下文”。事实上,canvas的背景是我们要油漆的,不是canvas本身。
var c1 = document.getElementById("c1");
var c1_context = c1.getContext("2d");
让我们选择用红漆(fillStyle = " # f00 ";)和油漆100 px宽度和高度的红场。(fillRect(50、50、100、100))。
c1_context.fillStyle = "#f00";
c1_context.fillRect(50, 50, 100, 100);
“上下文”描述的方法
fillstyle css色彩、模式或梯度内的形状。默认fillStyle坚实的黑色。
strokestyle颜色或形状的CSS样式
fillRect(x,y,宽度、高度)画一个矩形从x和y坐标和宽度x高度的大小。
strokeRect(x,y,宽度、高度)画一个矩形,只有它的边缘。
clearRect(x,y,宽度、高度)明确指定的区域在x,y坐标和区域宽度x高度
<div ><canvas id="Canvas2" width="200" height = "200" style="border:solid 1px #000000;"></canvas>
<div>
<button οnclick="blue_square_2();return true;">Blue Square</button>
<button οnclick="red_stroke_2();return true;">Red Square</button>
<button οnclick="clear_rect_2();return true;">Erase Everything</button>
</div>
</div>
<script>
var c2 = document.getElementById("c2");
var c2_context = c2.getContext("2d");
function blue_square_2() { //Blue color square
c2_context.fillStyle = "#00f";
c2_context.fillRect(50, 50, 100, 100);
}
function red_stroke_2() { //Red color edges
c2_context.strokeStyle = "#f00";
c2_context.strokeRect(45, 45, 110, 110);
}
function clear_rect_2() { //Clear all
c2_context.clearRect(40, 40, 120, 120);
}
</script>