<canvas>
標籤咱們先用之前的知識畫一個簡略的,用的是div標籤,簡略版 一個簡單的小demo, canvas
默認的大小是300*150css
HTML代碼以下html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<canvas id="canvas" width="300px" height="300px">
</canvas>
</body>
</html>
複製代碼
JavaScript代碼以下:canvas
var isPainting = false;
var canvas =document.getElementById("canvas");
canvas.onmousedown = function(msg){
isPainting = true;
var x = msg.clientX;
// console.log(x);
var y = msg.clientY;
// console.log(y);
var context = canvas.getContext('2d');
context.beginPath();
context.arc(x, y, 1, 0, 360);
context.fill();
};
canvas.onmousemove = function(msg){
if(isPainting){
var x = msg.clientX;
var y = msg.clientY;
var context = canvas.getContext('2d');
context.beginPath();
context.arc(x, y, 1, 0, 360);
context.fill();
} else{
}
}
canvas.onmouseup = function(msg){
isPainting = false;
}
複製代碼
主要的是如下幾句:bash
var context = canvas.getContext('2d'); //canvas的上下文環境
context.beginPath(); //開始畫圖
context.arc(x, y, 1, 0, 360); //畫一個圓,圓心座標是(x, y) 半徑1px,從0度到 360度。若是是其餘數是3.141592678
context.fill(); //填充
複製代碼
繪製Rectangle 矩形spa
context.stroke() //只畫邊界
context.fillStyle = 'red'; //用紅色填充 //這句話要在前面,由於要先畫上去
fillRect(x,y,width,height) //畫一個矩形
strokeRect(x,y,width,height) //畫一個矩形邊框
clearRect(x,y,width,height) //清楚規定大小的矩形
複製代碼
body默認的margin是8px,會影響你作圓時的位置,避免這個bug就把這個margin設置爲0 code
你想定位的座標是 (9,8),這個座標是相對於視口的,也就是說是相對於HTML那個的,若是你在canvas裏面做圖必然影響 去除以後要想作出全屏的canvas,必定不能用width='100wh' height='100vh',由於這個會等比縮放cdn