美文网首页Web 前端开发 前端开发
canvas实现的简易涂鸦板效果

canvas实现的简易涂鸦板效果

作者: 小pxu | 来源:发表于2016-06-04 20:59 被阅读1148次

用canvas实现的简易涂鸦板效果,用鼠标点击在画布上随意涂鸦

<head>
<meta charset="UTF-8">
<title>涂鸦</title>
<style>
*{
margin: 0;
padding: 0;
}
#canvas1{
box-shadow: 0 5px 40px black;
}
</style>
</head>
<body>
<canvas id="canvas1" width="500" height="500"></canvas>
</body>
<script>
var canvas = document.getElementById('canvas1');

var context = canvas.getContext('2d')

canvas.onmousedown = function (e) {
    
    var ev = e||window.event;

    var x = ev.clientX - canvas.offsetLeft;
    var y = ev.clientY - canvas.offsetTop;

    context.beginPath();
    context.moveTo(x,y);

    canvas.onmousemove = function (e) {
        var ev = e||window.event;
        var x = ev.clientX - canvas.offsetLeft;
        var y = ev.clientY - canvas.offsetTop;
        console.log(x)
        context.lineWidth = 5;
        context.strokeStyle = "red";

        context.lineTo(x,y);
        context.stroke()
    }
    canvas.onmouseup = function () {
        canvas.onmousemove = null;
    }
}

</script>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>涂鸦</title>
    <style>
        #canvas1{
            box-shadow: 0 5px 40px black;
        }
    </style>
</head>
<body>
    <canvas id="canvas1" width="500" height="500"></canvas>
</body>
<script>
    var canvas = document.getElementById('canvas1');

    var context = canvas.getContext('2d')

    canvas.onmousedown = function (e) {
        
        var ev = e||window.event;

        var x = ev.clientX - canvas.offsetLeft;
        var y = ev.clientY - canvas.offsetTop;

        context.beginPath();
        context.moveTo(x,y);

        canvas.onmousemove = function (e) {
            var ev = e||window.event;
            var x = ev.clientX - canvas.offsetLeft;
            var y = ev.clientY - canvas.offsetTop;
            console.log(x)
            context.lineWidth = 5;
            context.strokeStyle = "red";

            context.lineTo(x,y);
            context.stroke()
        }
        canvas.onmouseup = function () {
            canvas.onmousemove = null;
        }
    }

</script>
</html>

相关文章

网友评论

    本文标题:canvas实现的简易涂鸦板效果

    本文链接:https://www.haomeiwen.com/subject/rzukdttx.html