方法1:查看演示 點擊鼠標做畫html
此方法就是鼠標移動的時候不停的畫小圓點,而後用等粗的線將小圓點串起來(有點相似於珍珠項鍊)。由於是小圓點,因此效果要比方法2好,比較平滑。canvas
方法2:查看演示 點擊鼠標做畫瀏覽器
這個方法很容易理解,就是不斷的將鼠標所在的位置用線段連起來。缺點是不夠平滑,尤爲是粗線條的時候。this
方法1:spa
- <!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:.net
- <!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>