我正在尝试使用动态 js 框架构建一个非常基本的绘画应用程序。一切进展顺利,直到我尝试合并一个形状函数,该函数允许用户单击舞台以指定圆的中心点,拖动并释放鼠标以计算半径,然后将变量传递给构造函数并输出形状。
我的代码似乎运行良好,我将圆形对象打印到控制台,它的变量是我期望的,但由于某种原因它没有出现在我的舞台上!
下面是我的全部代码。关于圆的方法是朝向底部的。谁能明白为什么它没有出现在舞台上?!
<script src="kinetic-v4.0.4.js"></script>
<script src="utils.js"></script>
<script>
//variables
var stage;
var canvas;
var context;
var mouse;
var startX, startY, endX, endY;
var rad;
var dx, dy;
//run when the page is loaded
function init(){
//Create a stage object
stage = new Kinetic.Stage({
container: 'canvas',
height: 400,
width: 400,
draggable: true,
});
//References
//get references to elements within the body
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
//Capture the coordinates of the mouse in relation to the canvas
mouse = utils.captureMouse(canvas);
//Add listener to stage.
stage.getContainer().addEventListener("mousedown", mouseDown, false);
}
function mouseDown(){
console.log("mousedown");
stage.getContainer().addEventListener("mousemove", mouseMove, false);
context.beginPath();
}
function mouseMove(){
console.log("mousemove");
stage.getContainer().addEventListener("mouseup", mouseUp, false);
context.lineTo(mouse.x, mouse.y);
context.stroke();
}
function mouseUp(){
console.log("mouseup");
stage.getContainer().removeEventListener("mousemove", mouseMove, false);
context.closePath();
}
function circle(){
//add listeners.
stage.getContainer().addEventListener("mousedown", getCircleStart, false);
}
function getCircleStart(){
startX = mouse.x;
startY = mouse.y;
console.log("START POINTS: X: " + startX + " " + "Y: " + startY);
stage.getContainer().addEventListener("mouseup", getCircleEnd, false);
}
function getCircleEnd(){
endX = mouse.x;
endY = mouse.y;
console.log("END POINTS: X: " + endX + " " + "Y: " + endY);
dx = endX - startX;
dy = endY - startY;
console.log(dx + " " + dy);
rad = Math.pow(dx, 2) + Math.pow(dy, 2);
rad = Math.sqrt(rad);
console.log("radius: " + rad);
//create layer for circle
var layer = new Kinetic.Layer();
//draw circle
var circle = new Kinetic.Circle({
x: startX,
y: startY,
radius: rad,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
visible: true
});
//add to layer
layer.add(circle);
//add layer to stage
stage.add(layer);
console.log(circle);
}
utils.js -> http://paulirish.com/2011/requestanimationframe-for-smart-animating/