2017-06-21 24 views
0

私のスクリプトで助けが必要です。私はcanvasの上でマウスと一緒に "明るい場所"を動かそうとしていますが、それはcoursorよりも速く動いているようです。問題はどこだ?キャンバス放射状勾配アニメーション

<!DOCTYPE HTML> 
<html> 
    <head> 
    <style> 
     body { 
    position:absolute; 
     margin: 0px; 
     padding: 0px; 
     } 
     canvas{ 
    position: fixed; 
    height:900px; 
    Width:900px; 
    } 

    </style> 
    </head> 
    <body> 
    <canvas id="myCanvas"></canvas> 
    <script> 
     var canvas = document.getElementById('myCanvas'); 
     var context = canvas.getContext('2d'); 
     window.onmousemove=function(){ 
     context.clearRect(0, 0, canvas.width, canvas.height); 
     context.rect(0, 0, canvas.width, canvas.height); 

     // create radial gradient 
     var grd = context.createRadialGradient(event.clientX, event.clientY, 5, event.clientX+20, event.clientY+20, 100); 
     // light blue 
     grd.addColorStop(0, '#ffffff'); 
     // dark blue 
     grd.addColorStop(0.5, '#000000'); 

     context.fillStyle = grd; 
     context.fill(); 
     }; 

    window.onclick= function(){ 
     alert("X: " + event.clientX + " " +"Y: " + event.clientY) 
    } 
    </script> 
    </body> 
</html> 
+1

あなたは、自身の幅と高さのプロパティを設定せずにCSSを使ってキャンバスのサイズを変更しています。コンテキストは、表示された(CSS)プロパティのサイズではなく、このプロパティのサイズのみを認識します。また、マウスの移動ごとにグラデーションを作成するのは、一般的には悪い考えです。代わりに、オフスクリーンキャンバスにグラデーションを1回描画してから、このオフスクリーンキャンバスを正しい位置に描画します。 – Kaiido

+0

これでOKです。ありがとうございました – Pawel

答えて

2

マウスイベントを保ち、マウスイベントが表示に同期されていないとして、別のレンダリング。マウスイベントはマウスの状態を記録します(1秒間に100+サンプル以上)。アニメーションフレームは、キャンバスのコンテンツを60fpsで表示できる場合にのみレンダリングされます。

グラデーションを一度作成し、2DキャンバスAPIのトランスフォーメーション関数を使用して移動してください。

また、キャンバスの解像度(キャンバス上のピクセル数)が、キャンバスが占めるCSSピクセルの数と一致することを確認してください。

// start the main loop when ready 
 
requestAnimationFrame(mainLoop); 
 
// get the canvas context 
 
const ctx = can.getContext("2d"); 
 
// set up mouse 
 
document.addEventListener("mousemove", mEvent); 
 
function mEvent(e) { mouse.x = e.pageX; mouse.y = e.pageY } 
 
const mouse = { x: 0, y: 0 }; 
 
// create gardient 
 
const grad = ctx.createRadialGradient(0, 0, 0, 0, 0, 100); 
 
grad.addColorStop(0, "rgb(255,255,255)"); 
 
grad.addColorStop(1, "rgb(0,0,0)"); 
 
// requestAnimationFrame callback function 
 
function mainLoop() { 
 
    // resize canvas if needed 
 
    if (can.width !== innerWidth || can.height !== innerHeight) { 
 
    can.width = innerWidth; // resize canvas if 
 
    can.height = innerHeight; // window resized 
 
    } 
 
    // set canvas origin to the mouse coords (moves the gradient) 
 
    ctx.setTransform(1, 0, 0, 1, mouse.x, mouse.y); 
 
    ctx.fillStyle = grad; 
 
    // fill canvas with a rectangle 
 
    ctx.fillRect(-mouse.x, -mouse.y, can.width, can.height); 
 
    requestAnimationFrame(mainLoop); 
 
}
canvas { 
 
    position: absolute; 
 
    top: 0px; 
 
    left: 0px; 
 
}
<canvas id="can"></canvas>

関連する問題