我想用kinetic js框架構建一個非常基本的繪畫應用程序。 直到我試圖合併一個形狀函數,允許用戶點擊舞臺上指定圓心點,拖動並釋放鼠標來計算半徑,然後將變量傳遞到構造函數並輸出形狀時,所有工作都進行得很順利。使用動力學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/
看來JSFiddle現在正在運行,但我會盡力讓一個儘快確認我的答案,如果沒有其他人在我之前找到解決方案! –
嘿,我試着把.draw()函數放在你建議的位置,不幸的是它沒有改變任何東西。 Circle對象仍然在創建,只是沒有出現在舞臺上......我添加了我的控制檯的屏幕截圖,添加了圓圈,並且您可以看到它具有x,y,並且它的可見屬性設置爲true!我不知道發生了什麼事! – Javacadabra
你能製作一個JSFiddle嗎?沒有你的utils.js我不能做很多事情。 –