■ mouse wheel event 時に画面scroll を防止する [JavaScript版]

 mouse wheel動作を利用して画面の拡大等の処理を行う場合、画面がスクロールして困ることがある。
 これを防止する方法をネット上で見つけたので、それを用いた sample program を示す。

● mouse wheel で図形の回転を行う。

scroll 防止


● sample program  (下記赤字部分が scroll 関連)
//-------------------------------------------
// srl: prevent scroll when mouse wheel event
//-------------------------------------------
  var df1;
  var g, w, h;
  var theta = 0;

//..........................
  function init() {
//..........................
    df1 = document.form1;
    loadCanvas();

    paint();
  }

//..........................
  function loadCanvas() {
//..........................
    var canvas = document.getElementById("canvas");
    if(!canvas.getContext) {
      alert("not supported");
      return;
    }

    g = canvas.getContext("2d");
    g.lineWidth = 1;
    g.font = "12px 'MS 明朝'";
    w = canvas.width;
    h = canvas.height;

    canvas.addEventListener("mousewheel" , mouseWheel);
  }

//............................
  function mouseWheel(ee) {
//............................

    if(ee.preventDefault) {
      if(df1.chkS.checked) ee.preventDefault();  // <---
    }
    ee.returnValue = false;

    theta += 10*ee.wheelDelta/120;
    paint();
  }

//....................................
  function paint() { // 
//....................................
    g.clearRect(0, 0, w, h);

    g.translate(w/2, h/2);
    g.rotate(theta*Math.PI/180);
    g.translate(-w/2, -h/2);

    g.fillStyle = "blue";
    g.fillRect(w/4, h/4, w/2, h/2);
    g.fillText("...rotation...", w/4, h/4-3);

    g.setTransform(1, 0, 0, 1, 0, 0);
  }
ホーム