使用canvas来创建区域,建立核心对象,再接着分别获取几个按钮的节点,确定鼠标按下的起始位置,和鼠标释放时的位置,并为其加上移动事件,鼠标松开时则删除移动节点。点击清除画布按钮,使用clearRect清除画布。

代码如下,注释在其内,请君一阅。

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简易画图工具</title>
</head>
<style>
    section {
        width: 700px;
    }

    h1 {
        text-align: center;
    }

    canvas {
        margin-bottom: 20px;
    }
    aside{
        text-align: center;
    }
    aside>input{
        margin-right: 20px;
    }
</style>

<body>
    <section>
        <h1>简易画图工具</h1>
        <canvas id="canNode" width="700px" height="400px"></canvas>
        <aside>
            <input type="button" value="清除画布" class="clear">
            <input type="color" class="yanse">
            <input type="range" min="1" max="10" class="cuxi">
        </aside>
    </section>
    <script src="./hua.js"></script>
</body>

</html>

 

canNode.style.border = "3px solid red";
let pen = canNode.getContext("2d");
console.log(canNode.clientWidth, canNode.clientHeight);//canvas标签的填充盒尺寸  700、400
console.log(canNode.offsetLeft, canNode.offsetTop);//canvas节点距左侧和顶部的距离  8、72

//获取按钮节点
let clearEle = document.getElementsByClassName("clear")[0];
let colEle = document.getElementsByClassName("yanse")[0];
let cuxiEle = document.getElementsByClassName("cuxi")[0];

//鼠标按下时
canNode.addEventListener("mousedown", function (e) {
    let event = e || window.event;
    //获取鼠标起始位置
    let x1 = event.clientX - canNode.offsetLeft;
    let y1 = event.clientY - canNode.offsetTop;

    // console.log(event.offsetX, event.offsetY);
    // console.log(event.clientX, event.clientY);
    // console.log(event.clientX - canNode.offsetLeft, event.clientY - canNode.offsetTop);
    pen.beginPath();
    pen.moveTo(x1, y1);

    //鼠标移动时进行绘画
    canNode.addEventListener("mousemove", hua);

    //鼠标松开时则删除移动节点
    canNode.addEventListener("mouseup", function () {
        canNode.removeEventListener("mousemove", hua);
    });
});

//绘画移动
function hua(e) {
    let event = e || window.event;
    let x2 = event.offsetX;
    let y2 = event.offsetY;
    pen.lineTo(x2, y2);
    pen.strokeStyle = colEle.value;
    pen.lineWidth = cuxiEle.value;
    pen.stroke();
}

//清除画布
clearEle.addEventListener("click", function () {
    pen.clearRect(0,0,canNode.clientWidth, canNode.clientHeight);
});

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐