var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
var isDown=false;
var range=makeRangeControl(50,40,200,25);
drawRangeControl(range);
canvas.onmousedown=(function(e){handleMouseDown(e);});
canvas.onmousemove=(function(e){handleMouseMove(e);});
canvas.onmouseup=(function(e){handleMouseUpOut(e);});
canvas.onmouseout=(function(e){handleMouseUpOut(e);});
function makeRangeControl(x,y,width,height){
var range={x:x,y:y,width:width,height:height};
range.x1=range.x+range.width;
range.y1=range.y;
//
range.pct=0.50;
return(range);
}
function drawRangeControl(range){
// clear the range control area
// bar
ctx.lineWidth=6;
ctx.lineCap='round';
ctx.beginPath();
ctx.moveTo(range.x,range.y);
ctx.lineTo(range.x1,range.y);
ctx.strokeStyle='black';
ctx.stroke();
// thumb
ctx.beginPath();
var thumbX=range.x+range.width*range.pct;
ctx.moveTo(thumbX,range.y-range.height/2);
ctx.lineTo(thumbX,range.y+range.height/2);
ctx.strokeStyle='rgba(255,0,0,0.25)';
ctx.stroke();
// legend
ctx.fillStyle='blue';
ctx.textAlign='center';
ctx.textBaseline='top';
ctx.font='10px arial';
ctx.fillText(parseInt(range.pct*100)+'%',range.x+range.width/2,range.y-range.height/2-2);
}
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// get mouse position
var mx=parseInt(e.clientX-offsetX);
var my=parseInt(e.clientY-offsetY);
// test for possible start of dragging
isDown=(mx>range.x && mx<range.x+range.width && my>range.y-range.height/2 && my<range.y+range.height/2);
}
function handleMouseUpOut(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// stop dragging
isDown=false;
}
function handleMouseMove(e){
if(!isDown){return;}
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// get mouse position
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// set new thumb & redraw
range.pct=Math.max(0,Math.min(1,(mouseX-range.x)/range.width));
ctx.clearRect(range.x-12.5,range.y-range.height/2-15,range.width+25,range.height+20);
drawRangeControl(range);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Drag the thumb on the range control</h4>
<canvas id="canvas" width=512 height=512></canvas>
ブリリアント応答は、どうもありがとうございました。私はスライダに基づいてビットマップを操作する方法を見つけなければなりません。スライダの値を使って再描画する必要があると思います。すなわち、 'var leftPos = 0'変数を設定してから、' ctx.drawimage(img、leftPos、0); ' を使ってスライダの位置に基づいてイメージを再描画します。もしあなたがそれについて何か考えているなら教えてください。 @JamiePatt。 – JamiePatt
はい、範囲コントロールの値が変更されたとき(mousemove)、キャンバスをクリアし、imgを適切な 'leftPos'オフセットで再描画し、範囲コントロールを再描画します。あなたのプロジェクトに幸運を祈る! :-) – markE