如何在画布上获得图像的坐标?

时间:2017-07-13 16:30:53

标签: javascript html5 canvas



function writeMessage(canvas, message) {
		var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.font = '12pt Calibri';
    context.fillStyle = 'black';
    context.fillText(message, 10, 25);
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
}

function make_base() {
  base_image = new Image();
  base_image.src = 'https://www.w3schools.com/css/img_fjords.jpg';
  base_image.onload = function() {
    context.drawImage(base_image, 0, 0);
  }
}

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
make_base();

canvas.addEventListener('mousemove', function(evt) {
    var mousePos = getMousePos(canvas, evt);
    var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
    writeMessage(canvas, message);
}, false);

<canvas id="myCanvas" width="500" height="500" style="border:1px solid #000000;">
</canvas>
&#13;
&#13;
&#13;

我可以在画布上添加图像,并在鼠标悬停在画布上时获取画布的坐标。

但是当我悬停在照片上时,图像会消失。

1 个答案:

答案 0 :(得分:1)

问题是,每次在绘制文本(消息)之前清除整个画布,这样也会清除图像。

要解决此问题,您需要在清除画布后和绘制文本之前重新绘制图像...

&#13;
&#13;
function writeMessage(canvas, message) {
   var context = canvas.getContext('2d');
   context.clearRect(0, 0, canvas.width, canvas.height);
   context.drawImage(base_image, 0, 0); //<-- draw image
   context.font = '12pt Calibri';
   context.fillStyle = 'red';
   context.fillText(message, 10, 25);
}

function getMousePos(canvas, evt) {
   var rect = canvas.getBoundingClientRect();
   return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
   };
}

function make_base() {
   base_image = new Image();
   base_image.src = 'https://www.w3schools.com/css/img_fjords.jpg';
   base_image.onload = function() {
      context.drawImage(base_image, 0, 0);
   }
}

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
make_base();

canvas.addEventListener('mousemove', function(evt) {
   var mousePos = getMousePos(canvas, evt);
   var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
   writeMessage(canvas, message);
}, false);
&#13;
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #000000;"></canvas>
&#13;
&#13;
&#13;