【发布时间】:2012-03-20 12:05:21
【问题描述】:
我们一直在使用 canvas 元素,但在 Mobile Safari 上遇到了迟缓,而该应用在桌面上运行流畅。
测试应用非常原始。它只是让用户在桌面上使用鼠标或在智能手机上使用手指画一条线。
在 Mobile Safari 中,线条的绘制通常非常生涩。一行的第一位将实时渲染,但其余的直到手指离开屏幕后才会渲染。
有什么想法吗?
代码如下。
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css' />
<script src='http://code.jquery.com/jquery-1.6.4.min.js'></script>
<script src='http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js'></script>
<style type='text/css'>
#canvas { border:1px solid red }
</style>
</head>
<body>
<div id='draw_page' data-role='page'>
<canvas id="canvas" width="500" height="350"></canvas>
</div>
<script type="text/javascript">
$('#draw_page').live('pageinit', function() {
prep_canvas();
});
</script>
</body>
</html>
JavaScript:
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
var canvas;
var context;
function prep_canvas() {
canvas = $('#canvas')[0];
context = canvas.getContext("2d");
}
$('#canvas').live('vmousedown', function(e){
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
$('#canvas').live('vmousemove', function(e){
if(paint){
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
$('#canvas').live('vmouseup', function(e){
paint = false;
});
function addClick(x, y, dragging)
{
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
function redraw(){
canvas.width = canvas.width; // Clears the canvas
context.strokeStyle = "black";
context.lineJoin = "round";
context.lineWidth = 2;
for(var i=0; i < clickX.length; i++)
{
context.beginPath();
if(clickDrag[i] && i){
context.moveTo(clickX[i-1], clickY[i-1]);
}else{
context.moveTo(clickX[i]-1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.stroke();
}
}
【问题讨论】:
-
确保您没有在 iPhone 模拟器上进行测试。此外,以全屏模式运行画布或作为通过 PhoneGap 移植的应用程序运行将导致 iOS 5 中的 JavaScript 像 iOS 4 一样运行。
-
另外,还有一种方法可以使用多层画布来避免必须重绘每一帧中的所有内容,这在移动浏览器中非常麻烦。如果您有两个相互重叠的画布层,您可以经常将当前线绘制到后面的画布上,然后只将线的最新部分绘制到前面的画布上。
-
希望我能提供更多帮助。看起来这里的答案有一个现场演示,你可以在手机上尝试,我不认为这个人每次都在重绘画布:stackoverflow.com/questions/7478501/…
标签: iphone ios html canvas mobile-safari