更新时间:2023-11-24 09:19:04
考虑鼠标位置怎么样?
看看这个漂亮的教程: http://simonsarris.com/ blog / 510-making-html5-canvas-useful [ ^ ],它是关于您尝试学习的内容。
What about taking into account the mouse position also?
Take a look on this nice tutorial: http://simonsarris.com/blog/510-making-html5-canvas-useful[^], it is about what you try to learn.
x和y坐标是固定的,因此它一直在同一个地方绘制。
研究这个示例代码并进行调整:
The x and y coordinates are fixed, so it kept drawing on the same place.
Study this sample code and adapt:
<!DOCTYPE HTML>
<html>
<head>
<title>Coding Canvas</title>
</head>
<body>
<canvas id="mycanvas" width="350" height="200" style="border:1px solid #000000; margin:20px;">
Oops! This browser does not support the HTML5 canvas tag.
</canvas>
<script>
var canvas=document.getElementById('mycanvas');
var context=canvas.getContext('2d');
function drawRec(x, y){
context.beginPath();
context.rect(x, y, 80, 50);
context.stroke();
}
// get x, y coordinates of double clicking
function getPosition(e) {
var rect = canvas.getBoundingClientRect();
return {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
}
// add event listener on double click to canvas
canvas.addEventListener('dblclick', function(e) {
var position = getPosition(e);
drawRec(position.x, position.y);
});
</script>
</body>
</html>
了解更多: HTML5初学者指南& CSS3 - 编码画布 [ ^ ]
我假设您的代码正在运行,panX,panY和context正在定义其他地方。
通过查看代码,每次在画布上双击时,矩形就会被重新绘制。
我假设panX和panY正在填充并且应该以某种方式表示鼠标位置,这似乎不适用于您的示例。
我已修改代码以使其使用jQuery工作。
I assume your code is working and panX, panY and context are being define some other place.
From looking at the code, every time there is a double click on the canvas the rectangle is being re-drawn over itself.
I assume the panX and panY are being populated and should represent the mouse position somehow, which does not appear to be working in your example.
I have modified the code to get it to work using jQuery.
#canvas {border:solid 1px green;}
<canvas id="canvas" width="300" height="300"></canvas>