使用鼠标在HTML5画布上绘制

171

我想使用鼠标在HTML画布上绘图(例如,签名、姓名的绘制...)

我该如何实现这个功能?


1
检查一下! https://dev59.com/R1DTa4cB1Zd3GeqPMMgQ - Nitesh
参见:如何在画布上手绘? - Martin Thoma
好问题。谢谢。 - Titus Sutio Fanpula
1
一个相关的问题:在画布上绘制后,如何将鼠标位置存储并发送到服务器以记录(重新跟踪)绘图? - Ben L
13个回答

310

这里是一个可用的示例。

 <html>
    <script type="text/javascript">
    var canvas, ctx, flag = false,
        prevX = 0,
        currX = 0,
        prevY = 0,
        currY = 0,
        dot_flag = false;

    var x = "black",
        y = 2;
    
    function init() {
        canvas = document.getElementById('can');
        ctx = canvas.getContext("2d");
        w = canvas.width;
        h = canvas.height;
    
        canvas.addEventListener("mousemove", function (e) {
            findxy('move', e)
        }, false);
        canvas.addEventListener("mousedown", function (e) {
            findxy('down', e)
        }, false);
        canvas.addEventListener("mouseup", function (e) {
            findxy('up', e)
        }, false);
        canvas.addEventListener("mouseout", function (e) {
            findxy('out', e)
        }, false);
    }
    
    function color(obj) {
        switch (obj.id) {
            case "green":
                x = "green";
                break;
            case "blue":
                x = "blue";
                break;
            case "red":
                x = "red";
                break;
            case "yellow":
                x = "yellow";
                break;
            case "orange":
                x = "orange";
                break;
            case "black":
                x = "black";
                break;
            case "white":
                x = "white";
                break;
        }
        if (x == "white") y = 14;
        else y = 2;
    
    }
    
    function draw() {
        ctx.beginPath();
        ctx.moveTo(prevX, prevY);
        ctx.lineTo(currX, currY);
        ctx.strokeStyle = x;
        ctx.lineWidth = y;
        ctx.stroke();
        ctx.closePath();
    }
    
    function erase() {
        var m = confirm("Want to clear");
        if (m) {
            ctx.clearRect(0, 0, w, h);
            document.getElementById("canvasimg").style.display = "none";
        }
    }
    
    function save() {
        document.getElementById("canvasimg").style.border = "2px solid";
        var dataURL = canvas.toDataURL();
        document.getElementById("canvasimg").src = dataURL;
        document.getElementById("canvasimg").style.display = "inline";
    }
    
    function findxy(res, e) {
        if (res == 'down') {
            prevX = currX;
            prevY = currY;
            currX = e.clientX - canvas.offsetLeft;
            currY = e.clientY - canvas.offsetTop;
    
            flag = true;
            dot_flag = true;
            if (dot_flag) {
                ctx.beginPath();
                ctx.fillStyle = x;
                ctx.fillRect(currX, currY, 2, 2);
                ctx.closePath();
                dot_flag = false;
            }
        }
        if (res == 'up' || res == "out") {
            flag = false;
        }
        if (res == 'move') {
            if (flag) {
                prevX = currX;
                prevY = currY;
                currX = e.clientX - canvas.offsetLeft;
                currY = e.clientY - canvas.offsetTop;
                draw();
            }
        }
    }
    </script>
    <body onload="init()">
        <canvas id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>
        <div style="position:absolute;top:12%;left:43%;">Choose Color</div>
        <div style="position:absolute;top:15%;left:45%;width:10px;height:10px;background:green;" id="green" onclick="color(this)"></div>
        <div style="position:absolute;top:15%;left:46%;width:10px;height:10px;background:blue;" id="blue" onclick="color(this)"></div>
        <div style="position:absolute;top:15%;left:47%;width:10px;height:10px;background:red;" id="red" onclick="color(this)"></div>
        <div style="position:absolute;top:17%;left:45%;width:10px;height:10px;background:yellow;" id="yellow" onclick="color(this)"></div>
        <div style="position:absolute;top:17%;left:46%;width:10px;height:10px;background:orange;" id="orange" onclick="color(this)"></div>
        <div style="position:absolute;top:17%;left:47%;width:10px;height:10px;background:black;" id="black" onclick="color(this)"></div>
        <div style="position:absolute;top:20%;left:43%;">Eraser</div>
        <div style="position:absolute;top:22%;left:45%;width:15px;height:15px;background:white;border:2px solid;" id="white" onclick="color(this)"></div>
        <img id="canvasimg" style="position:absolute;top:10%;left:52%;" style="display:none;">
        <input type="button" value="save" id="btn" size="30" onclick="save()" style="position:absolute;top:55%;left:10%;">
        <input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">
    </body>
    </html>


14
为什么要使用开关语句?你也可以使用 x = obj.id 来实现,完成了。 - MarijnS95
1
我正在尝试使用这段代码,但是当我没有将页面滚动到底部时,绘图在垂直方向上存在问题。我应该在这段代码中更改什么? - Cameron Darlington
10
为了解决滚动问题,我将canvas.offsetLeft;canvas.offsetTop;分别更改为canvas.getBoundingClientRect().left;canvas.getBoundingClientRect().top; - KWILLIAMS
2
这段代码让我朝着正确的方向迈出了第一步。但是我必须说,这段代码相当粗糙且难看。对于任何在鼠标位置上遇到困难的人,请查看此答案:https://dev59.com/pGQn5IYBdhLWcg3wETk5#17130415 - LuqJensen
2
要让它能够与绘图笔(如绘画板)一起使用,必须使用触摸事件替换鼠标事件,例如touchmovetouchstarttouchend,然后在findxy()代码中使用e.touches["0"].clientX来获取clientX。但我还没有想到一种简单的方法来检测正在使用的是什么,因为根据我的测试,无法同时监听两个事件。我保留了mouseout。虽然不完美,但它确实可以工作。 - Jacob David C. Cunningham
显示剩余8条评论

86

我认为,这里的其他例子都太复杂了。这个例子更简单,而且只涉及JS...

// create canvas element and append it to document body
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);

// some hotfixes... ( ≖_≖)
document.body.style.margin = 0;
canvas.style.position = 'fixed';

// get canvas 2D context and set him correct size
var ctx = canvas.getContext('2d');
resize();

// last known position
var pos = { x: 0, y: 0 };

window.addEventListener('resize', resize);
document.addEventListener('mousemove', draw);
document.addEventListener('mousedown', setPosition);
document.addEventListener('mouseenter', setPosition);

// new position from mouse event
function setPosition(e) {
  pos.x = e.clientX;
  pos.y = e.clientY;
}

// resize canvas
function resize() {
  ctx.canvas.width = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
}

function draw(e) {
  // mouse left button must be pressed
  if (e.buttons !== 1) return;

  ctx.beginPath(); // begin

  ctx.lineWidth = 5;
  ctx.lineCap = 'round';
  ctx.strokeStyle = '#c0392b';

  ctx.moveTo(pos.x, pos.y); // from
  setPosition(e);
  ctx.lineTo(pos.x, pos.y); // to

  ctx.stroke(); // draw it!
}


1
@RyanCameron.Me 只是注释掉了这一行代码:if (e.buttons !== 1) return; ;-). - Matěj Pokorný
1
@RyanCameron.Me 刚刚尝试了最新版本的 Chrome、Firefox 和 Edge,一切正常... 你用什么浏览器? - Matěj Pokorný
1
@RyanCameron.Me 更可能是因为我的resize函数。我根据窗口大小设置画布的宽度和高度。你应该根据你的<div class="container-fluid">来设置这些值。 - Matěj Pokorný
1
感谢您的帮助!这有助于在设置位置函数中从y坐标中减去约250。 - RyanCameron.Me
4
这很好,但是对画布的定位做了一些假设。更通用的方式是:var rect = canvas.getBoundingClientRect(); pos.x = e.clientX - rect.left; pos.y = e.clientY - rect.top; - darma
显示剩余8条评论

48

以下是使用canvas创建绘图应用程序的最简单方法:

  1. mousedown, mousemovemouseup事件侦听器附加到画布DOM。
  2. mousedown中,获取鼠标坐标,并使用moveTo()方法定位绘图光标和beginPath()方法开始新的绘图路径。
  3. mousemove中,不断使用lineTo()将新点添加到路径中,并使用stroke()为最后一段着色。
  4. mouseup中,设置一个标志来禁用绘图。

从那里开始,您可以添加各种其他功能,例如让用户能够选择线条粗细、颜色、刷子笔触,甚至是图层。


1
如果有beginPath,那么在mouseup之后应该有closePath吗? - Timo
2
@Timo 当你使用 stroke() 时,它会自动关闭路径。 - Random_Pythoneer59

13

我也想将这种方法用于签名,我在http://codetheory.in/上找到了一个示例。

我已经将以下代码添加到了jsfiddle中。

Html:

<div id="sketch">
    <canvas id="paint"></canvas>
</div>

JavaScript:

 (function() {
    var canvas = document.querySelector('#paint');
    var ctx = canvas.getContext('2d');

    var sketch = document.querySelector('#sketch');
    var sketch_style = getComputedStyle(sketch);
    canvas.width = parseInt(sketch_style.getPropertyValue('width'));
    canvas.height = parseInt(sketch_style.getPropertyValue('height'));

    var mouse = {x: 0, y: 0};
    var last_mouse = {x: 0, y: 0};

    /* Mouse Capturing Work */
    canvas.addEventListener('mousemove', function(e) {
        last_mouse.x = mouse.x;
        last_mouse.y = mouse.y;

        mouse.x = e.pageX - this.offsetLeft;
        mouse.y = e.pageY - this.offsetTop;
    }, false);


    /* Drawing on Paint App */
    ctx.lineWidth = 5;
    ctx.lineJoin = 'round';
    ctx.lineCap = 'round';
    ctx.strokeStyle = 'blue';

    canvas.addEventListener('mousedown', function(e) {
        canvas.addEventListener('mousemove', onPaint, false);
    }, false);

    canvas.addEventListener('mouseup', function() {
        canvas.removeEventListener('mousemove', onPaint, false);
    }, false);

    var onPaint = function() {
        ctx.beginPath();
        ctx.moveTo(last_mouse.x, last_mouse.y);
        ctx.lineTo(mouse.x, mouse.y);
        ctx.closePath();
        ctx.stroke();
    };

}());

1
最好的部分是你可以通过在不同位置右键单击来绘制直接连接的直线。 :) - Aidiakapi
不支持触摸屏,这里指的不是平板电脑,而是指同时具备鼠标和触摸屏的 Windows 10 笔记本电脑。 - Paul
我得到了一个错误:Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'。 - Timo

7

我必须为这个主题提供一个简单的例子,所以我在这里分享:

http://jsfiddle.net/Haelle/v6tfp2e1

class SignTool {
  constructor() {
    this.initVars()
    this.initEvents()
  }

  initVars() {
    this.canvas = $('#canvas')[0]
    this.ctx = this.canvas.getContext("2d")
    this.isMouseClicked = false
    this.isMouseInCanvas = false
    this.prevX = 0
    this.currX = 0
    this.prevY = 0
    this.currY = 0
  }

  initEvents() {
    $('#canvas').on("mousemove", (e) => this.onMouseMove(e))
    $('#canvas').on("mousedown", (e) => this.onMouseDown(e))
    $('#canvas').on("mouseup", () => this.onMouseUp())
    $('#canvas').on("mouseout", () => this.onMouseOut())
    $('#canvas').on("mouseenter", (e) => this.onMouseEnter(e))
  }
  
  onMouseDown(e) {
   this.isMouseClicked = true
    this.updateCurrentPosition(e)
  }
  
  onMouseUp() {
   this.isMouseClicked = false
  }
  
  onMouseEnter(e) {
   this.isMouseInCanvas = true
    this.updateCurrentPosition(e)
  }
  
  onMouseOut() {
   this.isMouseInCanvas = false
  }

  onMouseMove(e) {
    if (this.isMouseClicked && this.isMouseInCanvas) {
     this.updateCurrentPosition(e)
      this.draw()
    }
  }
  
  updateCurrentPosition(e) {
      this.prevX = this.currX
      this.prevY = this.currY
      this.currX = e.clientX - this.canvas.offsetLeft
      this.currY = e.clientY - this.canvas.offsetTop
  }
  
  draw() {
    this.ctx.beginPath()
    this.ctx.moveTo(this.prevX, this.prevY)
    this.ctx.lineTo(this.currX, this.currY)
    this.ctx.strokeStyle = "black"
    this.ctx.lineWidth = 2
    this.ctx.stroke()
    this.ctx.closePath()
  }
}

var canvas = new SignTool()
canvas {
  position: absolute;
  border: 2px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="500" height="300"></canvas>


这是一个很好的例子,课堂上很容易理解!我将它转换为纯JavaScript,以避免加载额外的糟糕的jQuery!谢谢!!! - undefined

6

这里是我简单的画布绘制和擦除示例。

https://jsfiddle.net/richardcwc/d2gxjdva/

//Canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//Variables
var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;
var last_mousex = last_mousey = 0;
var mousex = mousey = 0;
var mousedown = false;
var tooltype = 'draw';

//Mousedown
$(canvas).on('mousedown', function(e) {
    last_mousex = mousex = parseInt(e.clientX-canvasx);
 last_mousey = mousey = parseInt(e.clientY-canvasy);
    mousedown = true;
});

//Mouseup
$(canvas).on('mouseup', function(e) {
    mousedown = false;
});

//Mousemove
$(canvas).on('mousemove', function(e) {
    mousex = parseInt(e.clientX-canvasx);
    mousey = parseInt(e.clientY-canvasy);
    if(mousedown) {
        ctx.beginPath();
        if(tooltype=='draw') {
            ctx.globalCompositeOperation = 'source-over';
            ctx.strokeStyle = 'black';
            ctx.lineWidth = 3;
        } else {
            ctx.globalCompositeOperation = 'destination-out';
            ctx.lineWidth = 10;
        }
        ctx.moveTo(last_mousex,last_mousey);
        ctx.lineTo(mousex,mousey);
        ctx.lineJoin = ctx.lineCap = 'round';
        ctx.stroke();
    }
    last_mousex = mousex;
    last_mousey = mousey;
    //Output
    $('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);
});

//Use draw|erase
use_tool = function(tool) {
    tooltype = tool; //update
}
canvas {
    cursor: crosshair;
    border: 1px solid #000000;
}
<canvas id="canvas" width="800" height="500"></canvas>
<input type="button" value="draw" onclick="use_tool('draw');" />
<input type="button" value="erase" onclick="use_tool('erase');" />
<div id="output"></div>


5
在纯JavaScript中,没有使用position:absolute的超简洁版本在这里。主要思路是将画布的上下文移动到正确的坐标并绘制一条线。取消下面的mousedownmousemove事件处理程序的注释并注释掉click事件处理程序,以了解它的工作原理。
<!DOCTYPE html>
<html>
<body>

<p style="margin: 50px">Just some padding in y direction</p>

<canvas id="myCanvas" width="300" height="300" style="background: #000; margin-left: 100px;">Your browser does not support the HTML5 canvas tag.</canvas>

<script>
    const c = document.getElementById("myCanvas");
    // c.addEventListener("click", penTool); // fires after mouse left btn is released
    c.addEventListener("mousedown", setLastCoords); // fires before mouse left btn is released
    c.addEventListener("mousemove", freeForm);


    const ctx = c.getContext("2d");

    function setLastCoords(e) {
        const {x, y} = c.getBoundingClientRect();
        lastX = e.clientX - x;
        lastY = e.clientY - y;
    }

    function freeForm(e) {
        if (e.buttons !== 1) return; // left button is not pushed yet
        penTool(e);
    }

    function penTool(e) {
        const {x, y} = c.getBoundingClientRect();
        const newX = e.clientX - x;
        const newY = e.clientY - y;

        ctx.beginPath();
        ctx.lineWidth = 5;
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(newX, newY);
        ctx.strokeStyle = 'white';
        ctx.stroke();
        ctx.closePath();

        lastX = newX;
        lastY = newY;
    }

    let lastX = 0;
    let lastY = 0;  
</script>

</body>
</html>

3
重要的是,不要在CSS中设置宽度和高度,因为这样只会拉伸画布而不是重新调整大小。- https://dev59.com/c17Va4cB1Zd3GeqPNM-l#8693791 - Nitin

3

这个问题已经问了很多年,并且已经得到了解答。

对于任何寻找简单绘图画布的人(例如,从用户/客户那里获取签名),我在这里发布了当前被接受答案更简化的jQuery版本。

$(document).ready(function() {
  var flag, dot_flag = false,
 prevX, prevY, currX, currY = 0,
 color = 'black', thickness = 2;
  var $canvas = $('#canvas');
  var ctx = $canvas[0].getContext('2d');

  $canvas.on('mousemove mousedown mouseup mouseout', function(e) {
    prevX = currX;
    prevY = currY;
    currX = e.clientX - $canvas.offset().left;
    currY = e.clientY - $canvas.offset().top;
    if (e.type == 'mousedown') {
      flag = true;
    }
    if (e.type == 'mouseup' || e.type == 'mouseout') {
      flag = false;
    }
    if (e.type == 'mousemove') {
      if (flag) {
        ctx.beginPath();
        ctx.moveTo(prevX, prevY);
        ctx.lineTo(currX, currY);
        ctx.strokeStyle = color;
        ctx.lineWidth = thickness;
        ctx.stroke();
        ctx.closePath();
      }
    }
  });

  $('.canvas-clear').on('click', function(e) {
    c_width = $canvas.width();
    c_height = $canvas.height();
    ctx.clearRect(0, 0, c_width, c_height);
    $('#canvasimg').hide();
  });
});
<html>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
  <body>
    <canvas id="canvas" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>
    <input type="button" value="Clear" class="canvas-clear" />
  </body>
</html>


3

我采用了第一个答案,并根据我的需求进行了修改。现在:

  1. 在移动设备上也可以使用。
  2. 更具响应能力。
  3. 滚动没有问题。

 <html>
  <head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
    <style>
        .selected::before {

           content: 'x';
           height: 30px;
           width: 30px;
           left: 18px;
           top: -8px;
           font-size: 3rem;
           position: absolute;
        }

        .select-colour{
          height: 30px;
          width: 30px;
        }

    </style>
 </head>
    <script type="text/javascript">
    var canvas, ctx, flag = false,
        prevX = 0,
        currX = 0,
        prevY = 0,
        currY = 0,
        dot_flag = false;

    var x = "black",
        y = 2;
    
    function init() {
        canvas = document.getElementById('can');
        ctx = canvas.getContext("2d");
        w = canvas.width;
        h = canvas.height;
    
        canvas.addEventListener("mousemove", function (e) {
            findxy('move', e, '')
        }, false);
        canvas.addEventListener("mousedown", function (e) {
            findxy('down', e, '')
        }, false);
        canvas.addEventListener("mouseup", function (e) {
            findxy('up', e, '')
        }, false);
        canvas.addEventListener("mouseout", function (e) {
            findxy('out', e, '')
        }, false);

        canvas.addEventListener("touchmove", function (e) {
            findxy('move', e, 'touch')
        }, false);
        canvas.addEventListener("touchstart", function (e) {
            findxy('down', e, 'touch')
        }, false);
        canvas.addEventListener("touchend", function (e) {
            findxy('up', e, 'touch')
        }, false);    

    }
    
    function color(obj) {        
        x = obj.id; 
        if (x == "white") y = 14;
        else y = 2;
        var prevSelected = document.getElementsByClassName("selected");
        // If it exists, remove it.
        if(prevSelected.length > 0) { 
          prevSelected[0].classList.remove("selected");
        }
                 
       document.getElementById(obj.id).classList.add("selected");
    }
    
    function draw() {
        ctx.beginPath();
        ctx.moveTo(prevX, prevY);
        ctx.lineTo(currX, currY);
        ctx.strokeStyle = x;
        ctx.lineWidth = y;
        ctx.stroke();
        ctx.closePath();
    }
    
    function erase() {
        var m = confirm("Want to clear");
        if (m) {
            ctx.clearRect(0, 0, w, h);
            document.getElementById("canvasimg").style.display = "none";
        }
    }
    
    function save() {
        document.getElementById("canvasimg").style.border = "2px solid";
        var dataURL = canvas.toDataURL();
        document.getElementById("canvasimg").src = dataURL;
        document.getElementById("canvasimg").style.display = "inline";
    }

    function download() {
        var link = document.createElement('a');
        var dataURL = canvas.toDataURL();
        link.href = dataURL;
        link.download = 'mydrawing.png';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
    
    function findxy(res, e, source) {
        if(source){
            var clientX = e.changedTouches[0].clientX;
            var clientY = e.changedTouches[0].clientY;
        }else{
            var clientX = e.clientX;
            var clientY = e.clientY;
        }

        if (res == 'down') {
            prevX = currX;
            prevY = currY;
            currX = clientX - canvas.getBoundingClientRect().left;
            currY = clientY - canvas.getBoundingClientRect().top;
    
            flag = true;
            dot_flag = true;
            if (dot_flag) {
                ctx.beginPath();
                ctx.fillStyle = x;
                ctx.fillRect(currX, currY, 2, 2);
                ctx.closePath();
                dot_flag = false;
            }
        }

        if (res == 'up' || res == "out") {
            flag = false;
        }

        if (res == 'move') {
            if (flag) {
                prevX = currX;
                prevY = currY;
                currX = clientX - canvas.getBoundingClientRect().left;
                currY = clientY - canvas.getBoundingClientRect().top;
                draw();
            }
        }
    }
    </script>
  <body onload="init()">
        <div style="">
                <div style="float: left;">
                   <canvas id="can" width="600" height="500" style=" border:5px solid;"></canvas>
                </div>
                <div style="margin-left:20px; float:left;">
                    <div class="row">
                        <div class="col-12">Choose Color</div>
                        <div class="col-2 pt-3"><div class="select-colour" style="background:green;" id="green" onclick="color(this)"></div></div>
                       <div class="col-2 pt-3"><div class="select-colour" style="background:blue;" id="blue" onclick="color(this)"></div></div>
                       <div class="col-2 pt-3"><div class="select-colour" style="background:red;" id="red" onclick="color(this)"></div></div>
                       <div class="col-2 pt-3"><div class="select-colour" style="background:yellow;" id="yellow" onclick="color(this)"></div></div>
                       <div class="col-2 pt-3"><div class="select-colour" style="background:orange;" id="orange" onclick="color(this)"></div></div>
                       <div class="col-2 pt-3"><div class="select-colour" style="background:black;" id="black" onclick="color(this)"></div></div>
                       <div class="col-12 pt-3 pb-3" style="">Eraser</div>
                       <div class="col-2 pt-3"><div class="select-colour" style="background:white;border:2px solid;" id="white" onclick="color(this)"></div></div>
                </div>

                <div class="row">
                    <div class="col-6 col-lg-12 mt-3">
                        <input type="button" value="Download" id="download" size="23" onclick="download()" class="btn btn-primary">
                    </div>
                    <div class="col-6 col-lg-12 mt-3">
                            <input type="button" value="clear" id="clr" size="23" onclick="erase()" class="btn btn-light">
                    </div>          
                </div>
           </div>

        </div>
    </body>
    </html>


3

还要查看这个:
示例:
https://github.com/williammalone/Simple-HTML5-Drawing-App

文档:
http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/

本文档包括以下代码:

HTML:

<canvas id="canvas" width="490" height="220"></canvas>

JS:

context = document.getElementById('canvas').getContext("2d");

$('#canvas').mousedown(function(e){
  var mouseX = e.pageX - this.offsetLeft;
  var mouseY = e.pageY - this.offsetTop;
        
  paint = true;
  addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
  redraw();
});

$('#canvas').mouseup(function(e){
  paint = false;
});

$('#canvas').mouseleave(function(e){
  paint = false;
});

var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;

function addClick(x, y, dragging)
{
  clickX.push(x);
  clickY.push(y);
  clickDrag.push(dragging);
}

//Also redraw
function redraw(){
  context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas
  
  context.strokeStyle = "#df4b26";
  context.lineJoin = "round";
  context.lineWidth = 5;
            
  for(var i=0; i < clickX.length; i++) {        
    context.beginPath();
    if(clickDrag[i] && i){
      context.moveTo(clickX[i-1], clickY[i-1]);
     }else{
       context.moveTo(clickX[i]-1, clickY[i]);
     }
     context.lineTo(clickX[i], clickY[i]);
     context.closePath();
     context.stroke();
  }
}

另一个很棒的例子:
http://perfectionkills.com/exploring-canvas-drawing-techniques/

这个链接是关于探索Canvas绘图技术的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接