我在拖动范围滑块时尝试在画布中移动圆圈。我拖动时无法移动圆圈。
我可以让它移动,但旧圈子没有被删除所以我可以很多圈子。我知道我可以使用 clearRect ,但无法理解在哪里使用它......
代码如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Hello World!">
<meta name="author" content="Me">
<title>Hello World!</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="400">Not supported content</canvas>
<input type="range" id="length" name="length" min="-100" max="100" oninput="updateTextInput(this.value);">
<input type="text" id="textInput" value="">
<script>
var cnv = document.getElementById("myCanvas");
var g = cnv.getContext("2d");
g.lineWidth = 3;
g.strokeStyle = "#000000"; //black
g.fillStyle = "#FF5500"; //red
g.beginPath();
g.arc(100, 100, 50, 0, 2*Math.PI);
g.fill();
g.stroke();
function updateTextInput(val) {
document.getElementById('textInput').value=val;
g.beginPath();
var placement = val;
g.arc(placement, 100, 50, 0, 2*Math.PI);
g.fill();
g.stroke();
}
g.beginPath();
g.moveTo(100, 50);
g.lineTo(300, 50);
g.stroke();
g.beginPath();
g.moveTo(100, 150);
g.lineTo(300, 150);
g.stroke();
</script>
</body>
答案 0 :(得分:0)
您的context.clearRect
就在您开始新图纸之前......
以下是一种方式:http://jsfiddle.net/m1erickson/c2g52w9q/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.lineWidth=8;
ctx.strokeStyle='blue';
var PI2=Math.PI*2;
var cx=150;
var cy=150;
var radius=50;
draw(0);
var $percent=$('#percent');
$percent.on('change',function(){
draw(parseInt($percent.val()));
});
function draw(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(cx+x);
}
}); // end $(function(){});
</script>
</head>
<body>
<input type=range id=percent min=-50 value=0 max=50 step=1><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>