用canvas画坐标轴,并且几点某个位置获取坐标

碰上一个需求:要给pdf的某一页的某个位置加上水印,要知道具体的位置

1.画坐标轴,让运营人员根据坐标轴配(按横纵的百分比来配)

2.直接点击canvas上的某个位置直接获取到位置

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>秃头小宝贝</title>
<style type="text/css">
canvas {
    border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="tutou" width="580" height="840"></canvas>
<script type="text/javascript">
function draw(){
    var canvas = document.getElementById('tutou');
    if(!canvas.getContext) return;
    var  ctx= canvas.getContext("2d");
	const height=canvas.height
	const width=canvas.width
	const num=canvas.width/100
	const numH=canvas.height/100
	
	//绘制横轴坐标
	ctx.beginPath()
	ctx.moveTo(0,0)
	ctx.lineTo(width,0)
	ctx.strokeStyle='red'
	ctx.stroke()
	
	for(let i=0;i<=10;i++){
		ctx.moveTo(num*i*10,0)
		ctx.lineTo(num*i*10,10)
		 ctx.fillStyle = 'red';
		if(i==0){
			ctx.fillText(i*10,num*i*10,20)
		}else if(i==10){ctx.fillText(i*10,num*i*10-18,20)}
		else{
		ctx.fillText(i*10,num*i*10-5,20)}
	}
	ctx.strokeStyle='red'
	ctx.stroke()
	
	//绘制纵轴坐标
	ctx.beginPath()
	ctx.moveTo(0,5)
	ctx.lineTo(0,height)
	ctx.stroke()
	for(let i=0;i<=10;i++){
		ctx.moveTo(0,numH*i*10)
		ctx.lineTo(10,numH*i*10)
		 ctx.fillStyle = 'red';
		if(i==0){
			ctx.fillText(i*10,20,numH*i*10)
		}else if(i==10){ctx.fillText(i*10,12,numH*i*10)}
		else{
		ctx.fillText(i*10,12,numH*i*10+5)}
	}
	ctx.strokeStyle='red'
	ctx.stroke()
	// 添加点击事件监听器
        canvas.addEventListener('click', function(event) {
            // 获取 Canvas 的边界
            const rect = canvas.getBoundingClientRect();

            // 计算鼠标点击位置相对于 Canvas 的坐标
            const x = event.clientX - rect.left;
            const y = event.clientY - rect.top;

            // 输出坐标
            console.log(`Clicked position: x=${x}, y=${y}`);

            // 在点击位置绘制一个小圆圈(可选)
            ctx.fillStyle = 'red';
            ctx.beginPath();
            ctx.arc(x, y, 5, 0, Math.PI * 2);
            ctx.fill();
        });
 
   
}
draw();
</script>
</body>
</html>

效果图:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值