canvas涂鸦Demo(基于jquery)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>canvas涂鸦Demo</title> 
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
    
<div align="center">
    <canvas id="myCanvas" width="500" height="200" style="border:2px solid #6699cc"></canvas>
    <div class="control-ops">
    <button type="button" class="btn btn-primary" onclick="javascript:clearArea();return false;">清空画板</button>
    Line width : <select id="selWidth">
        <option value="1">1</option>
        <option value="3">3</option>
        <option value="5">5</option>
        <option value="7">7</option>
        <option value="9" selected="selected">9</option>
        <option value="11">11</option>
    </select>
    Color : <select id="selColor">
        <option value="black">black</option>
        <option value="blue" selected="selected">blue</option>
        <option value="red">red</option>
        <option value="green">green</option>
        <option value="yellow">yellow</option>
        <option value="gray">gray</option>
    </select>
    </div>
</div>
    
<script>
var mousePressed = false;
var lastX, lastY;
var ctx;
 
function InitThis() {
    ctx = document.getElementById('myCanvas').getContext("2d");
 
    $('#myCanvas').mousedown(function (e) {
        mousePressed = true;
        Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
    });
 
    $('#myCanvas').mousemove(function (e) {
        if (mousePressed) {
            Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
        }
    });
 
    $('#myCanvas').mouseup(function (e) {
        mousePressed = false;
    });
        $('#myCanvas').mouseleave(function (e) {
        mousePressed = false;
    });
}
 
function Draw(x, y, isDown) {
    if (isDown) {
        ctx.beginPath();
        ctx.strokeStyle = $('#selColor').val();
        ctx.lineWidth = $('#selWidth').val();
        ctx.lineJoin = "round";
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        ctx.closePath();
        ctx.stroke();
    }
    lastX = x; lastY = y;
}
     
function clearArea() {
    // Use the identity matrix while clearing the canvas
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
    
$(document).ready(function(){
  InitThis()
});
</script>

</body>
</html>

效果:

 

 转自:http://www.htmleaf.com/ziliaoku/qianduanjiaocheng/201502101363.html

posted @ 2020-11-12 15:09  Mankii  阅读(215)  评论(0编辑  收藏  举报
返回顶部