canvas 实现十字线

1,097 阅读1分钟

canvas 实现十字线

offset坐标

style

<style type="text/css">
        body{
                margin: 0;
        }
        canvas{
                background-color: black;
                margin: 10px;
        }
</style>

html

<canvas width="500" height="500" id="canvas"></canvas>

script

<script>
    let canvas = document.querySelector("#canvas");
    let ctx = canvas.getContext("2d"); //绘制环境
    let width = canvas.width;
    let height = canvas.height;
    let x = width / 2, //x中心点
        y = height / 2, //y中心店
        dx = 0, //上次结束的x点
        dy = 0; //上次结束的y点
    let offset = 10; //线与线顶点之间的距离
    
    canvas.addEventListener("mousedown",e=>{
        x = e.offsetX;
        y = e.offsetY;
        draw(x,y,width,height);
        canvas.addEventListener("mousemove",listenMouseMove);
    })

    canvas.addEventListener("mouseup",e=>{
        canvas.removeEventListener("mousemove",listenMouseMove);
        x = dx;
        y = dy;
    });
    function listenMouseMove(e){
        dx = x + (e.offsetX - x);
        dy = y + (e.offsetY - y);
        draw(dx,dy,width,height);
    }
    function draw(x,y,w = 500,h = 500){
        ctx.clearRect(0,0,w,h);
        let high = (h / 2);
        let wide = (w / 2);
        let dx = (wide - x);
        let dy = (high - y);
        drawLine({ //上线
                color : "#38f",
                x : x,
                y : 0,
                dx : x,
                dy : high - offset - dy
        });
        drawLine({//下线
                color : "green",
                x : x,
                y : high + offset - dy,
                dx : x,
                dy : h
        });
        drawLine({//左线
                color : "#f20",
                x : 0,
                y : y,
                dx : wide - offset - dx,
                dy : y
        });
        drawLine({//右线
                color : "orange",
                x : wide + offset - dx,
                y : y,
                dx : w,
                dy : y
        });
        //圆心
        ctx.beginPath();
        ctx.strokeStyle = "red";
        ctx.arc(x,y,offset - 3 ,0,2 * Math.PI); //圆绘制
        ctx.closePath();
        ctx.stroke();
    }
    function  drawLine(options = {}) {
        ctx.beginPath(); //开始路径
        ctx.strokeStyle = options.color; //空心样式颜色
        ctx.moveTo(options.x,options.y); //把笔移动到哪个点开始
        ctx.lineTo(options.dx,options.dy); //把笔绘制到哪个点结束
        ctx.closePath(); //结束路径
        ctx.stroke(); //空心绘制
    }
    draw(x,y,width,height);
</script>

利用offset是比较容易实现,不需要考虑元素与页面的距离。

client 坐标

大致和上面一样的,不同就是要换算而已。

let x = e.clientX - canvas.offsetLeft;
let y = e.clientY - canvas.offsetTop + 1; //不加1会比offsetY少一像素
let dx = x + (e.clientX - canvas.offsetLeft - x);
let dy = y + (e.clientY - canvas.offsetTop + 1 - y);

效果都一样的,写这个只是为了铺垫,好在cornerstoneTools.js中写自己的效果。写的比较烂,勿喷。 效果如下:

image.png