<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
要想作出全屏的canvas,必定不能用width='100wh' height='100vh',由于这个会等比缩放cdn