使用范围输入控制 canvas 对象位置
To control canvas object position with range inputs
我可以使用范围滑块输入水平移动对象。我可以使用范围滑块输入垂直移动对象。我正在使用变量 cx(圆 X)和 cy(圆 Y)来记录圆的 X、Y 位置,这根据调整轴的需要而起作用,但另一个轴总是恢复到 150,即 var cx = 150。意味着变量 cx 没有更新值。
使用的JS是:
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.lineWidth=6;
ctx.strokeStyle='green';
var PI2=Math.PI*2; //place the circle on canvas
var cx = 150; //these are the initial value but not updated when moved?
var cy = 150;
var radius=3;
drawX(0);
drawY(0);
var $xpos=$('#xpos');
$xpos.on('change',function(){
drawX(parseInt($xpos.val()));
console.log("hori: " +xpos);
});
var $ypos=$('#ypos');
$ypos.on('change',function(){
drawY(parseInt($ypos.val()));
console.log("vert: " +ypos);
});
function drawX(x){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(cx+x,cy,radius,0,PI2);
ctx.closePath();
ctx.stroke();
console.log("Y axis: " + cy);
console.log("Y axis: " + cy);
}
function drawY(y){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(cx,cy+y,radius,0,PI2);
ctx.closePath();
ctx.stroke();
console.log("X axis: " +cx);
console.log("X axis: " +cy);
}
});
控件是应用于 canvas 对象的简单范围输入滑块:
<label>X-pos<input type=range id=xpos min=-170 value=0 max=170 step=1></label><br>
<label>Y-pos<input type=range id=ypos min=-170 value=0 max=170 step=1></label><br>
<canvas id="canvas" width=300 height=300></canvas>
因为你的两个函数都叫draw()
.
您只能使用一个名称声明一个函数,这样您的两个滑块将调用相同的函数并沿相同的方向移动矩形。
您需要给它们起唯一的名字。试试 drawX()
和 drawY()
.
我可以使用范围滑块输入水平移动对象。我可以使用范围滑块输入垂直移动对象。我正在使用变量 cx(圆 X)和 cy(圆 Y)来记录圆的 X、Y 位置,这根据调整轴的需要而起作用,但另一个轴总是恢复到 150,即 var cx = 150。意味着变量 cx 没有更新值。
使用的JS是:
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.lineWidth=6;
ctx.strokeStyle='green';
var PI2=Math.PI*2; //place the circle on canvas
var cx = 150; //these are the initial value but not updated when moved?
var cy = 150;
var radius=3;
drawX(0);
drawY(0);
var $xpos=$('#xpos');
$xpos.on('change',function(){
drawX(parseInt($xpos.val()));
console.log("hori: " +xpos);
});
var $ypos=$('#ypos');
$ypos.on('change',function(){
drawY(parseInt($ypos.val()));
console.log("vert: " +ypos);
});
function drawX(x){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(cx+x,cy,radius,0,PI2);
ctx.closePath();
ctx.stroke();
console.log("Y axis: " + cy);
console.log("Y axis: " + cy);
}
function drawY(y){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(cx,cy+y,radius,0,PI2);
ctx.closePath();
ctx.stroke();
console.log("X axis: " +cx);
console.log("X axis: " +cy);
}
});
控件是应用于 canvas 对象的简单范围输入滑块:
<label>X-pos<input type=range id=xpos min=-170 value=0 max=170 step=1></label><br>
<label>Y-pos<input type=range id=ypos min=-170 value=0 max=170 step=1></label><br>
<canvas id="canvas" width=300 height=300></canvas>
因为你的两个函数都叫draw()
.
您只能使用一个名称声明一个函数,这样您的两个滑块将调用相同的函数并沿相同的方向移动矩形。
您需要给它们起唯一的名字。试试 drawX()
和 drawY()
.