Overview sample

by Yoshiharu Kamata

HTML

<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.23/themes/base/jquery-ui.css">
<div class="main">
<canvas id="target"></canvas>
</div>
<div id="slider"></div>
<div class="overview">
    <canvas id="bg"></canvas>
    <div id="range"></div>
</div>
<div id="console"></div>

CSS

.main{
    margin: 20px;
}
.overview{
    border: 1px solid red;
    width: 150px;
    height: 75px;
    overflow: hidden;
    margin: 10px 10px 10px 320px;
}
#target {
  border: 1px solid blue;
}
#bg{
    position: absolute;
    width: 150px;
    height: 75px;
}
#slider{
    margin: 20px;
    width: 300px;
}
#range{
    background: #efefef;
    opacity: 0.5;
    border: 1px solid green;
}

CoffeeScript

$ ->
  x = 0
  y = 0
  scale = 200
  $target = $ "#target"
  cvs = $("#target").get 0
  ctx = cvs.getContext "2d"
  $bg = $ "#bg"
  bgCvs = $bg.get 0 
  bgCtx = bgCvs.getContext "2d"
  

  cw = cvs.width
  ch = cvs.height
  bgw = bgCvs.width
  bgh = bgCvs.height

  tww = $target.width()
  thh = $target.height()
  bgww = $bg.width()
  bghh = $bg.height()
  
  $range = $ "#range"
  $overview = $ ".overview"
  
  $range.draggable(
    containment: "parent"
    drag: (e,ui)->
      x = ui.position.left * scale /100*tww/bgww
      y = ui.position.top * scale/100*thh/bghh
      plot()
  )
  .on("click",->
    if $(@).draggable("option","disabled") 
      x = 0
      y = 0
      plot()
  )
  
  plot = ->
    ctx.clearRect 0,0,cw,ch
    ctx.save()
    ctx.translate -x,-y
    ctx.scale scale/100, scale/100
    ctx.strokeRect 20,20,160,110  
    ctx.restore()
    
    bgCtx.save()
    bgCtx.scale 100/scale*bgw/cw, 100/scale*bgh/ch
    bgCtx.drawImage cvs,x,y
    bgCtx.restore()
    
  range = ->
    w = bgww*100/scale
    h = bghh*100/scale
    sizeOver = $overview.width() <= w || $overview.height() <= h
    $range
      .width(w)
      .height(h)
      .draggable "option","disabled",sizeOver
    $range.css("top",0).css("left",0) if sizeOver
  
  plot()
  range()
  
  $("#slider").slider(
    value:200
    max: 200
    change: (e,ui)->
      scale = ui.value
      plot()
      range()
    )