问题描述
我使用的是 Canvas2D。当在全宽时绘制图形或对象工作正常,但是当我调整画布大小并尝试绘制另一条线时,可以说,鼠标的位置与在该位置绘制的线不对应。
这是我的代码:
<script>
function resize(){
$("#can").width($(window).width());
$("#can").height($(window).height());
perWindow = ($(document).width() / screen.width);
canvasWidth = $(window).width();
canvasHeight = $(window).height();
//canvas = document.getElementById("can");
//bounds = canvas.getBoundingClientRect();
}
$(document).ready(function(){
$(window).on("resize",function(){
resize();
});
});
</script>
<div style="width:100%;">
<canvas id="can"
style="border: 1px solid #333;background-color:#000000;"></canvas>
<div id="coords" style="position:absolute;left:0;top:0;"></div>
<div id="coords2" style="position:absolute;left:0;top:40px;"></div>
<div id="coords3" style="position:absolute;left:0;top:80px;"></div>
</div>
<script type="application/javascript">
var canvasWidth = $(window).width();
var canvasHeight = $(window).height();
var canvas = null;
var bounds = null;
var ctx = null;
var hasLoaded = false;
var startX = 0;
var startY = 0;
var mouseX = 0;
var mouseY = 0;
var isDrawing = false;
var existingLines = [];
var tmp = 0;
function draw(e) {
ctx.fillStyle = "#e6e6e6";
ctx.fillRect(0,canvasWidth,canvasHeight);
ctx.strokeStyle = "black";
ctx.linewidth = 2;
ctx.beginPath();
for (var i = 0; i < existingLines.length; ++i) {
var line = existingLines[i];
ctx.moveto(line.startX,line.startY);
ctx.lineto(line.endX,line.endY);
}
ctx.stroke();
if (isDrawing) {
ctx.strokeStyle = "darkred";
ctx.linewidth = 3;
ctx.beginPath();
ctx.moveto(startX,startY);
$("#coords3").text("X: " + (startX) + " Y: " + (startY));
ctx.lineto(mouseX,mouseY);
ctx.stroke();
}
}
function onmousedown(e) {
if (hasLoaded && e.button === 0) {
if (!isDrawing) {
startX = e.clientX - bounds.left;
startY = e.clientY - bounds.top;
if((perWindow * 100) < 100){
startX = (tmp * perWindow);
}else{
tmp = startX;
}
$("#coords2").text("X: " + (startX) + " Y: " + (startY));
isDrawing = true;
}
draw(e);
}
}
function onmouseup(e) {
if (hasLoaded && e.button === 0) {
if (isDrawing) {
existingLines.push({
startX: startX,startY: startY,endX: mouseX,endY: mouseY
});
isDrawing = false;
}
draw(e);
}
}
function onmousemove(e) {
if (hasLoaded) {
mouseX = e.clientX - bounds.left;
mouseY = e.clientY - bounds.top;
$("#coords").text("X: " + (mouseX) + " Y: " + (mouseY));
if (isDrawing) {
draw(e);
}
}
}
window.onload = function(e) {
canvas = document.getElementById("can");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.onmousedown = onmousedown;
canvas.onmouseup = onmouseup;
canvas.onmousemove = onmousemove;
bounds = canvas.getBoundingClientRect();
ctx = canvas.getContext("2d");
hasLoaded = true;
resize();
draw(e);
}
</script>
如何在画布调整大小或缩小时保持 x、y 位置?
我猜当画布缩小时,画布上的 x、y 位置也发生了变化
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)