WEB前端开发学习----10. canvas实现画板的两个方法
方法1:查看演示 点击鼠标作画
此方法就是鼠标移动的时候不停的画小圆点,然后用等粗的线将小圆点串起来(有点类似于珍珠项链)。因为是小圆点,所以效果要比方法2好,比较平滑。
方法2:查看演示 点击鼠标作画
这个方法很容易理解,就是不断的将鼠标所在的位置用线段连起来。缺点是不够平滑,尤其是粗线条的时候。
方法1:
- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8"/>
- </head>
- <body style="margin:0">
- <canvas id="canvas">请更新浏览器版本</canvas>
- <script>
- var canvas=document.getElementById("canvas");
- var cxt=canvas.getContext("2d");
- var radius=10;
- var falge=false;
- //画板大小为屏幕大小
- canvas.width=window.innerWidth;
- canvas.height=window.innerHeight;
- cxt.lineWidth=20;
- //添加监听对象
- canvas.addEventListener("mousedown", start);
- canvas.addEventListener("mouseup", stop);
- canvas.addEventListener("mousemove", putPoint);
- function putPoint(e){
- if(falge){
- cxt.lineTo(e.clientX, e.clientY);
- cxt.stroke();
- cxt.beginPath();
- cxt.arc(e.clientX, e.clientY, radius, 0, 360, false);
- cxt.fill();
- cxt.beginPath();
- cxt.moveTo(e.clientX, e.clientY);
- }
- }
- function start(e){
- falge=true;
- putPoint(e);
- }
- function stop(){
- falge=false;
- cxt.beginPath();
- }
- </script>
- </body>
- </html>
方法2:
- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body>
- <canvas width="900" height="500" id="canvas" style="border:1px solid black">请更新浏览器版本</canvas>
- <script >
- var canvas=document.getElementById("canvas");
- var cxt=canvas.getContext("2d");
- var flag=false
- cxt.lineWidth=20;
- canvas.onmousedown=function(evt){
- //alert(evt.pageX);
- //alert(this.offsetLeft);
- var startX=evt.clientX-this.offsetLeft;
- var startY=evt.clientY-this.offsetTop;
- cxt.beginPath();
- cxt.moveTo(startX, startY);
- flag=true;
- }
- canvas.onmousemove=function(evt){
- if(flag){
- var endX=evt.clientX-this.offsetLeft;
- var endY=evt.clientY-this.offsetTop;
- cxt.lineTo(endX, endY);
- cxt.stroke();
- }
- }
- canvas.onmouseup=function(){
- flag=false;
- }
- canvas.onmouseout=function(){
- flag=false;
- }
- </script>
- </body>
- </html>