Canvas元素是HTML5比较受欢迎的功能,这个元素负责在页面中设定一个区域,然后就可以通过JavaScript动态在这个区域绘制图形。
canvas 宽高不能使用样式设置,这个画布的宽高,必须使用html标签来设置
<canvas width="800" height="600"></canvas>
canvas{
background-color: oldlace;
}
获取canvas var canvas=document.querySelector("canvas");
获取这个元素的context——图像稍后将在此被渲染。
获取canvas上下文环境 var ctx=canvas.getContext("2d");
开始绘制路径 ctx.beginPath();
从哪一个点开始 ctx.moveTo(20,20);
绘制笔触线条到什么位置 ctx.lineTo(150,50);
通过线条绘制图形轮廓 ctx.stroke();
线条颜色 ctx.strokeStyle="red";
线条宽度 ctx.lineWidth=3;
线条线段端点样式 ctx.lineCap="round";
两线段连接处所显示的样子 ctx.lineJoin="round;"
lineCap有butt、round、square三种样式
lineJoin有round、bevel、miter(默认)三种样式
代码部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
background-color: beige;
}
canvas{
background-color: white;
margin: auto;
position: absolute;
left: 0;
right: 0;
}
</style>
</head>
<body>
<canvas width="800" height="600"></canvas>
<script>
var canvas=document.querySelector("canvas");
var ctx=canvas.getContext("2d");
canvas.addEventListener("mousedown",mouseHandler);
ctx.lineCap="round";
ctx.lineJoin="round";
ctx.strokeStyle="red";
ctx.lineWidth=3;
function mouseHandler(e){
if(e.type==="mousedown"){
ctx.moveTo(e.offsetX,e.offsetY);
canvas.addEventListener("mousemove",mouseHandler);
canvas.addEventListener("mouseup",mouseHandler);
}else if(e.type==="mousemove"){
ctx.lineTo(e.offsetX,e.offsetY);
}else if(e.type==="mouseup"){
canvas.removeEventListener("mousemove",mouseHandler);
canvas.removeEventListener("mouseup",mouseHandler);
}
ctx.stroke();
}
</script>
</body>
</html>
效果图