我今天的问题是问为什么当我切换单选按钮时,绘制圆圈不起作用。我正在创建一个绘画程序。请帮我解决这个问题。
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="300" height="200"></canvas>
<h2>Choose your drawing shape:</h2>
<p>
<input type="radio" name="shape" onclick="square=true;" checked="checked">Square
<input type="radio" name="shape" onclick="square=false;">Circle
</p>
<h2>Color Settings:</h2>
<input type="color" id="myColor" />
<form id="colorForm">
<h3>Basic Colours:</h3>
<p>
<input type="radio" name="color" value="black" checked="checked" />Black
<input type="radio" name="color" value="red" />Red
<input type="radio" name="color" value="orange" />Orange
<input type="radio" name="color" value="yellow" />Yellow
<input type="radio" name="color" value="green" />Green
<input type="radio" name="color" value="blue" />Blue
<input type="radio" name="color" value="purple" />Purple
<input type="radio" name="color" value="white" />Eraser (White)
</p>
</form>
<form id="sizeForm">
<h2>Size:</h2>
<p>
<input type="radio" name="size" value="10" />Big
<input type="radio" name="size" value="5" checked="checked" />Normal
<input type="radio" name="size" value="2" />Small
</p>
</form>
<button onclick="clearCanvas()">Clear Drawing</button>
的CSS:
#canvas {
border: 1px solid black;
cursor: crosshair;
}
h2,
h3 {
margin-bottom: 0;
}
h2 {
font-size: 1.1rem;
}
h3 {
font-size: 1rem;
}
和javascript:
var square = true; // Set
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var size = 5
var eraserSize = 5;
$('#colorForm input, #myColor').on('change', function() {
ctx.fillStyle = $(this).val();
});
$('#sizeForm input').on('change', function() {
size = $(this).val();
});
var drawRect = function (event) {
var posX = event.pageX - $(canvas).offset().left - 4
var posY = event.pageY - $(canvas).offset().top - 4
ctx.fillRect(posX, posY, size, size)
}
var drawCircle = function (event) {
var posX = event.pageX - $(canvas).offset().left
var posY = event.pageY - $(canvas).offset().top
ctx.beginPath();
ctx.arc(posX, posY, size - 1, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
}
function mouseDown(e) {
// We only care about mousemove on the canvas, not the whole page
if (square) {
$(canvas).on('mousemove', drawRect).on('mouseup', drawRect);
} else {
$(canvas).on('mousemove', drawCircle).on('mouseup', drawCircle);
}
// If the user mouseup outside of the canvas, we don't want to keep listening, so listen for mouseup on the whole page to remove our other drawing listeners
$('html').one('mouseup', function() { // "one" means that it will only fire once and will stop listening after that (cleanup for free)
$(canvas).off('mousemove').off('mouseup');
});
}
function clearCanvas() {
if (confirm("Are you sure you want to clear your drawing?") == true) {
ctx.clearRect(0, 0, 300, 300)
}
}
// We only care about mousedown on the canvas, not the whole page
$(canvas).on('mousedown', mouseDown);
请帮我解决这个问题。谢谢你的支持!!!