dimanche 19 avril 2015

HTML5 canvas-Drawing on axis positioned in the center on the canvas

I'm trying to draw on a canvas which already has an axis drawn on it. I need to draw a polygon n sides on either side of the axis. When i click and drag on the canvas, the shape needs to appear but it's not working. Here's the codes for the 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>


The transform.js:



var canvas, ctx;

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);


I can't find my mistake. Please help.


Aucun commentaire:

Enregistrer un commentaire