您好,我的标签Canvas存在问题。 我正在使用引导程序,我想创建一个具有图像的画布,在该图像中,单击鼠标后我可以画一个点,但是因为我正在使用引导程序,所以画布区域伸展且这些点不在同一位置,所以我单击了鼠标
$().ready(function() {
showImage();
$("#image").click(function(e) {
getMousePositionAtClick(e);
});
function showImage() {
var canvas = document.getElementById('image');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'images/Piantina.jpg';
img.onload = function() {
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
};
}
function getMousePositionAtClick(e) {
var rect = image.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
alert(rect.left);
alert(rect.top);
drawPoint(x, y);
}
function drawPoint(x, y) {
var ctx = document.getElementById("image").getContext("2d");
ctx.fillStyle = "#000";
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2, true);
ctx.fill();
}
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-lg-8" id="columnCanvas">
<div class="card card-body">
<canvas id="image"></canvas>
</div>
</div>
答案 0 :(得分:0)
如上面评论中所述,Canvas元素没有响应。另一方面,Bootstrap具有响应能力。因此,要停止缩放,我们可以设置大小。查看Canvas的规格,如果未指定,默认大小为300px / 150px。因此,从理论上讲,如果我们仅将Canvas CSS大小设置为300px / 150px,这也会阻止缩放,下面是一个示例。
$().ready(function() {
showImage();
$("#image").click(function(e) {
getMousePositionAtClick(e);
});
function showImage() {
var canvas = document.getElementById('image');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'images/Piantina.jpg';
img.onload = function() {
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
};
}
function getMousePositionAtClick(e) {
var rect = image.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
alert(rect.left);
alert(rect.top);
drawPoint(x, y);
}
function drawPoint(x, y) {
var ctx = document.getElementById("image").getContext("2d");
ctx.fillStyle = "#000";
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2, true);
ctx.fill();
}
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-lg-8" id="columnCanvas">
<div class="card card-body">
<canvas id="image" style="width:300px;height:150px"></canvas>
</div>
</div>