實例演示html
如今,咱們開始經過一個實例來學習使用畫布繪製矩形,圓,文本,圖片等功能先看看效果:canvas
創建HTML,並增長表格表單數組
先新建一個HTML的頁面,並增長表格表單控件函數
<!DOCTYPE HTML>學習
<html>code
<head>orm
<title>TweetShirt</title>htm
<meta charset="utf-8">blog
<style>事件
canvas{
border: 1px solid black;
}
</style>
<script src = "tweetshirt.js">
</script>
</head>
<body>
<h1>TweetShirt</h1>
<canvas id="tshirtCanvas" width="600" height="200">Please upgrade your browser to use TweetShirt!</canvas>
<form>
<p>
<label for="backgroudColor">選擇背景顏色: </label>
<select id = "backgroundColor">
<option value="white" selected="selected">白色</option>
<option value="black">黑色</option>
</select>
</p>
<p>
<label for="shape">選擇圖形: </label>
<select id = "shape">
<option value="none" selected="selected">無</option>
<option value="circles">圓形</option>
<option value="squares">正方形</option>
</select>
</p>
<p>
<label for="foregroundColor">選擇前景顏色: </label>
<select id = "foregroundColor">
<option value="black" selected="selected">黑色</option>
<option value="white">白色</option>
</select>
</p>
<p>
<input type="button" id="previewButton" value="預覽">
</p>
</form>
</body>
</html>
JavaScript的處理表單控件
新建一個JavaScript的文件tweetshirt.js,首先啓動預覽按鈕,這樣點擊這個按鈕時它就會調用一個JavaScript的函數來處理畫布繪製。
window.onload = function () {
var button = document.getElementById("previewButton");
button.onclick = previewHandler;
}
<!--預覽點擊事件-->
function previewHandler() {
var canvas = document.getElementById("tshirtCanvas");
var context = canvas.getContext("2d");
//繪製圖像以前,重置以前繪製的內容
fillBackgroudColor(canvas,context);
//查看界面選擇了哪一種顏色
var selectObj = document.getElementById("shape");
var index = selectObj.selectedIndex; //獲得表單控件選項的編號的數組
var shape = selectObj[index].value; //獲得選項的值
if (shape == "squares") {
for(var squares = 0 ; squares < 20; squares++) {
//繪製正方形
drawSquare(canvas,context);
}
}
if (shape == "circles") {
for(var circles = 0 ; circles < 20; circles++) {
//繪製圓
drawCircle(canvas,context);
}
}
//繪製文本
drawText(canvas,context);
//繪製圖片
drawImage(canvas,context);
}
function fillBackgroudColor(canvas,context) {
var selectObj = document.getElementById("backgroundColor");
var index = selectObj.selectedIndex;
var bgColor = selectObj[index].value;
//fillStyle保存畫布上完成繪製時所用的顏色,它是一個屬性而不是方法,因此須要設置而不是調用
context.fillStyle = bgColor;
context.fillRect(0,0,600,200);
}