2011-09-28 144 views
0

我最近一直与HTML 5和具体画布对象经历过了第一时间后的HTML 5画布的缓慢更新。问题与鼠标移动/鼠标点击事件

我似乎有与鼠标事件的一些问题。

该方案是具有不同颜色的背景面的网格随机变化。上面有一个云形状,我用它作为剪辑区域,只能看到云下的网格部分。 (想想形状奇特炬光)

的问题是,我试图用鼠标移动云区,它不与任何鼠标移动或鼠标点击事件顺利更新。似乎需要一两个框架才能跟上,而单车颜色似乎还在继续。

我曾尝试:

  • 取出随机颜色的加速。
  • 仅使用简单的形状进行裁剪。
  • 设置setInterval函数来更新每1ms

可以看出这里运行 - http://jsfiddle.net/mXrNk/14/

任何帮助,将不胜感激。可能丢失了一些明显的东西。

<script> 

const FPS = 60; 
var myimg = new Image(); 

window.addEventListener('click', clicked, true); 

var mouseX = 170; 
var mouseY = 80; 

window.onload = init; 

function init() { 

    canvas = document.getElementById('myCanvas'); 
    context = canvas.getContext('2d'); 

    myimg.src = "smile.png"; 

    setInterval(draw, 1000/FPS); 

} 

function draw() { 

    context.clearRect(0,0,canvas.width,canvas.height); 
    // draw cloud 
    context.beginPath(); // begin custom shape 
    context.moveTo(mouseX, mouseY); 
    context.bezierCurveTo(mouseX-40, mouseY+20, mouseX-40, mouseY+70, mouseX+60, mouseY+70); 
    context.bezierCurveTo(mouseX+80, mouseY+100, mouseX+150, mouseY+100, mouseX+170, mouseY+70); 
    context.bezierCurveTo(mouseX+250, mouseY+70, mouseX+250, mouseY+40, mouseX+220, mouseY+20); 
    context.bezierCurveTo(mouseX+260, mouseY-40, mouseX+200, mouseY-50, mouseX+170, mouseY-30); 
    context.bezierCurveTo(mouseX+150, mouseY-75, mouseX+80, mouseY-60, mouseX+80, mouseY-30); 
    context.bezierCurveTo(mouseX+30, mouseY-75, mouseX-20, mouseY-60, mouseX, mouseY); 
    context.closePath(); // complete custom shape 
    context.lineWidth = 5; 
    context.strokeStyle = "#0000ff"; 
    context.stroke(); 

    context.save(); 
    context.clip(); 

    for (i = 0; i<7; i++) { 
     for (j = 0; j < 13; j++) { 
      context.strokeRect(j*myimg.width, i*myimg.height, myimg.width, myimg.height); 
      context.fillStyle = rndColor(); 
      context.fillRect(j*myimg.width, i*myimg.height, myimg.width, myimg.height); 
      context.drawImage(myimg, j*myimg.width, i*myimg.height); 
      context.fillStyle = "black"; 
      context.font = "italic 10pt Arial "; 
      context.fillText((i*13)+j, j*myimg.width+5,i*myimg.width+15); 
     } 
    } 

    context.restore(); 

} 

function rndColor() { 
    return '#' + ('00000' + (Math.random() * 16777216 << 0).toString(16)).substr(-6); 
} 

function clicked(e) { 
    mouseX = e.pageX; 
    mouseY = e.pageY; 
} 

</script> 
+0

小提琴杀死铬糟糕! – Loktar

回答

3

Live Demo

我用setTimeout而非setInterval。如果在它完成之前尝试运行该函数时使用间隔,那么这些事件将会建立起来,并且在呼叫仍在建立时仍然继续尝试运行。

超时但只会调用该函数一次,那么你可以设置其他超时在函数的底部再次调用自身。这样做可以确保功能已完成,并且不会导致等待处理的呼叫累积。

也看看这篇文章,

https://simonsarris.com/increasing-performance-by-caching-paths-on-canvas/

其对缓存的路径。它实际上由我打赌会弹出并看到这个问题的Simon Sarris。

+0

非常感谢。就像我打算现在:) – Volv

+0

没有问题很高兴有帮助。 – Loktar

+0

那个链接是404:'( –