我正在尝试绘制已在其上绘制轴的画布。我需要在轴的两侧绘制n个边的多边形。当我在画布上单击并拖动时,需要显示形状,但它不起作用。 这是transform.html的代码:
<!DOCTYPE html>
<html>
<head>
<title>Drawing Application</title>
</head>
<body>
<center>
<canvas id="myCanvas" width="1100" height="550"></canvas>
<br><output id="out"></output>
</center>
<div id="controls">
<p><input type="radio" name="shape" value="polygon">Polygon</p>
</div>
<p><label>Polygon Sides: <input id="polygonSides" type="range" step="1" min="3" max="10"></label></p>
<script src="transform.js"></script>
</body>
</html>
transform.js:
var canvas,ctx,dragging = false ,dragStartLocation,snapshot,shapeBox,fillColor,lineWidth,strokeColor,canvasColor,clearCanvas;
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
var transX = canvas.width * 0.5;
var transY = canvas.height * 0.5;
ctx.translate(transX, transY);
ctx.fillRect(0, -transY, 1, canvas.height);
ctx.fillRect(-transX, 0, canvas.width, 1);
function dragStart(event) {
dragging = true;
dragStartLocation = getCanvasCoordinates(event);
takeSnapshot();
}
function drag(event) {
var position;
if (dragging === true) {
restoreSnapshot();
position = getCanvasCoordinates(event);
draw(position, "polygon");
}
}
function dragStop(event) {
dragging = false;
restoreSnapshot();
var position = getCanvasCoordinates(event);
draw(position, "polygon");
}
canvas.onmousemove = function(e) {
var pos = getMousePos(canvas, e);
out.innerHTML = 'X:' + pos.x + ' Y:' + pos.y;
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left - transX,
y: evt.clientY - rect.top - transY
};
}
function drawPolygon(position, sides, angle) {
var coordinates = [],
radius = Math.sqrt(Math.pow((dragStartLocation.x - position.x), 2) + Math.pow((dragStartLocation.y - position.y), 2)),
index = 0;
for (index = 0; index < sides; index++) {
coordinates.push({x: dragStartLocation.x + radius * Math.cos(angle), y: dragStartLocation.y - radius * Math.sin(angle)});
angle += (2 * Math.PI) / sides;
}
ctx.beginPath();
ctx.moveTo(coordinates[0].x, coordinates[0].y);
for (index = 1; index < sides; index++) {
ctx.lineTo(coordinates[index].x, coordinates[index].y);
}
ctx.closePath();
}
function draw(position) {
var shape = document.querySelector('input[type="radio"][name="shape"]:checked').value,
polygonSides = document.getElementById("polygonSides").value;
if (shape === "polygon") {
drawPolygon(position, polygonSides, Math.PI / 4);
}
else {
ctx.stroke();
}
}
canvas.addEventListener('mousedown', dragStart, false);
canvas.addEventListener('mousemove', drag, false);
canvas.addEventListener('mouseup', dragStop, false);
我找不到自己的错误。请帮忙。