如何解决HTML Canvas:移动touchmove性能问题
我正在用HTML Canvas制作一个简单的游戏,但是在开始在移动设备上进行测试时遇到了问题。
我想使拖放功能正常工作,非常简单的任务。
但是在移动设备上存在一个问题:如果我听touchmove
事件并以requestAnimFrame
方法将触摸坐标应用于画布上的任何对象,那么它的性能将达到5-10FPS。根本没有像预期的那样平滑地拖动对象。
我制作了一个超级简单的示例,没有任何效果,过滤器和复杂的数学运算。
https://codepen.io/mctester/pen/bGeGEQq
我使用Oneplus 7 Pro进行此测试(Snapdragon 855,12GB RAM),但是示例中可拖动的红色方块非常滞后。
如果我以中等速度从左上角向右下角拖动红色方块,会是什么样子。
/* SAMPLE ONLY FOR MOBILE DEVICE */
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = document.body.clientWidth; //document.width is obsolete
canvas.height = document.body.clientHeight; //document.height is obsolete
var drawing = false;
var mousePos = { x:0,y:0 };
var lastPos = mousePos;
// Set up touch events for mobile,etc
canvas.addEventListener("touchstart",function (e) {
drawing = true;
mousePos = getTouchPos(canvas,e);
lastPos = getTouchPos(canvas,e);
},false);
canvas.addEventListener("touchend",function (e) {
drawing = false;
},false);
canvas.addEventListener("touchmove",function (e) {
mousePos = getTouchPos(canvas,false);
// Get the position of a touch relative to the canvas
function getTouchPos(canvasDom,touchEvent) {
var rect = canvasDom.getBoundingClientRect();
return {
x: touchEvent.touches[0].clientX - rect.left,y: touchEvent.touches[0].clientY - rect.top
};
}
// Get a regular interval for drawing to the screen
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimaitonFrame ||
function (callback) {
window.setTimeout(callback,1000/60);
};
})();
function animate(currentTime) {
if (drawing) {
ctx.beginPath();
ctx.fillStyle = 'red';
ctx.rect(mousePos.x,mousePos.y,10,10);
ctx.fill();
ctx.closePath();
}
requestAnimFrame(animate);
}
requestAnimFrame(animate);
如何使用touchmove
事件为HTML Canvas中的拖放功能执行对象的平滑过渡?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。