前端canvas绘图,利用canvas在图片上面绘制标记以及给canvas添加点击事件。
需要实现的效果如下图:
首先需要一个承载的核心画布
<canvas id="canvas" width="800" height="600"></canvas>
全部代码:
<!DOCTYPE html>
<html lang="zh"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>canvas</title></head><body><canvas id="canvas" width="800" height="600"></canvas></body>
</html>
<script type="text/javascript">const canvas = document.getElementById('canvas');const ctx = canvas.getContext('2d');//绘制背景图var backgroundImg = new Image();backgroundImg.src = "ditu.png"; //可以是本地图片地址backgroundImg.onload = function() {//这里要注意,canvas.width,canvas.height要等于这个就是你的Canvas width heightctx.drawImage(this, 0, 0, canvas.width, canvas.height); // 绘制底图var topImg = new Image();//topImg.src = 'https://www.baidu.com/static/imgs/cw.jpg'; 此处可以网络地址topImg.src = "jizhong_n.png";topImg.onload = function() {var x = 680; // 假设你想在底图上的(680, 150)位置绘制上图var y = 150;ctx.drawImage(topImg, x, y); // 绘制上图}var topImg = new Image();topImg.src = "jizhong_n.png";topImg.onload = function() {var x = 580;var y = 250;ctx.drawImage(topImg, x, y); // 绘制上图}var topImg = new Image();topImg.src = "jizhong_n.png";topImg.onload = function() {var x = 130;var y = 350;ctx.drawImage(topImg, x, y); // 绘制上图}}//点击事件canvas.addEventListener('mousedown', function(e) {var x = e.offsetX,y = e.offsetY;// 检查点击的位置是否在蓝色矩形内if (x >= 684 && x <= 722 && y >= 152 && y <= 207) {alert('您点击了第1个蓝色区域!');}if (x >= 585 && x <= 621 && y >= 251 && y <= 310) {alert('您点击了第2个蓝色区域!');}console.log(x + "---" + y);});
</script>