我尝试创建一个交互式应用,让用户通过点击形状的不同按钮来选择他们想要的形状,然后让他们在画布上的任何位置绘制形状。
这部分没关系,但是当我点击一个不同的按钮来绘制一个形状时,似乎前一个形状与新形状一起出现并且似乎是重叠的。
这是图片:
如您所见,矩形和圆形重叠。
我尝试使用多层画布来修复它,但现在矩形按钮不起作用,圆形的形状没有出现在用户点击的位置,而是远离它30px。
以下是代码:
<!DOCTYPE html>
<html>
<head>
<script>
function initiateCanvasRectangle()
{
var ctx = document.getElementById('myCanvas1').getContext('2d');
ctx.canvas.addEventListener('mousemove', function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
});
ctx.canvas.addEventListener('click', function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
ctx.fillRect(mouseX,mouseY,100,50);
ctx.fillStyle = "purple";
});
}
function initiateCanvasCircle()
{
var ctx = document.getElementById('myCanvas2').getContext('2d');
ctx.canvas.addEventListener('mousemove', function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
});
ctx.canvas.addEventListener('click', function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
ctx.beginPath();
ctx.arc(mouseX, mouseY, 30, 0, 2 * Math.PI, false);
ctx.fillStyle = 'pink';
ctx.fill();
});
}
function rect(){
window.addEventListener('click', function(event) {
initiateCanvasRectangle();
});
}
function drawRect()
{
rect();
}
function circle(){
window.addEventListener('click', function(event) {
initiateCanvasCircle();
});
}
function drawCircle()
{
circle();
}
</script>
<style>
BUTTON.rect {
padding: 8px 8px 8px 32px;
font-family: Arial, Verdana;
background-color: white;
border:2px solid black;
}
#tbl {
border-collapse:collapse;
}
</style>
</head>
<body>
<table border="1" id="tbl">
<tr><td><button class="circle" onclick="drawCircle(); return true;" style="padding:20px 40px 20px 40px;">Circle</button>
</td>
<td>
<button class="rect" onclick="drawRect(); return true;" style="padding:20px 40px 20px 40px;"></button>
</td></tr>
</table>
<p>
<div style="position: relative;">
<canvas id="myCanvas1" width="1100" height="400" style="position: absolute; left: 0; top: 0; z-index: 0; border:1px solid black"></canvas>
<canvas id="myCanvas2" width="1100" height="400" style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>
</body>
</html>
你能告诉我如何解决它吗?任何帮助都感激不尽。感谢。