canvas绘制并导出图片(画笔)

// 绘制
    var canvas = document.getElementById("myCanvas");
    canvas.width=document.getElementById('drawLine').offsetWidth
    canvas.height=document.getElementById('drawLine').offsetHeight
    var drawLine = function(){
        // 设置背景透明并清除画布
        $('#drawLine').css('background',"transparent")
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0,0,canvas.width,canvas.height);

        var isDrawing = false;
        // 鼠标按下时开始绘制
        canvas.addEventListener("mousedown", function(e) {
            isDrawing = true;
            ctx.beginPath();
            ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
            ctx.stroke();
        });

        // 鼠标移动时继续绘制轨迹
        canvas.addEventListener("mousemove", function(e) {
            if (isDrawing) {
                ctx.strokeStyle = 'red'
                ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
                ctx.stroke();
            }
        });

        // 鼠标松开时结束绘制
        canvas.addEventListener("mouseup", function() {
            ctx.closePath();//结束路径绘制
            ctx.stroke();//对路径进行填充
            isDrawing = false;
        });
    }
    var exportImg = function(){
        var dataURL = canvas.toDataURL("image/png"); // 将canvas转换为data URL
        // 创建一个链接元素,并将data URL设置为链接的地址
        var link = document.createElement('a');
        link.href = dataURL;
        link.download = "transparent_image.png"; // 设置导出的图片文件名
        document.body.appendChild(link);
        console.log(dataURL,'link')
        link.click()
        document.body.removeChild(link)
        // $('#drawLine').css('background',"url("+"./img/transparent_image.png"+") center center no-repeat")
    }

你可能感兴趣的:(js,jquery,canvas,画笔)