I published a simple processing sketch to my website using processing.js but when I opened it on my iPhone and iPad it didn't work at all. I found a bit of javacript to make it work and it helped, but still mouseX gets the position of the finger in relation to the whole page and not to the canvas area, so it doesn't quite get the position right. What can I do?
The code is live here: http://mqvlm.github.io/blog/rect.html
Here's the javascript i'm using:
<canvas ontouchstart="touchStart(event);"
ontouchmove="touchMove(event);"
ontouchend="touchEnd(event);"
ontouchcancel="touchCancel(event);"
id="sketch" width="300" height="300" data-processing-sources="/code/rect.pde"> </canvas>
<script type="text/javascript">
var processingInstance;
function setProcessingMouse(event){
if (!processingInstance) {
processingInstance = Processing.getInstanceById('sketch');
}
var x = event.touches[0].pageX;
var y = event.touches[0].pageY;
processingInstance.mouseX = x;
processingInstance.mouseY = y;
};
function touchStart(event) {
event.preventDefault();
setProcessingMouse(event);
processingInstance.mousePressed();
};
function touchMove(event) {
event.preventDefault();
setProcessingMouse(event);
processingInstance.mouseDragged();
};
function touchEnd(event) {
event.preventDefault();
setProcessingMouse(event);
processingInstance.mouseReleased();
};
function touchCancel(event) {
event.preventDefault();
setProcessingMouse(event);
processingInstance.mouseReleased();
};
</script>
Instead of pageX
and pageY
, you should use screenX
and screenY
to get the position relative to the users screen:
var x = event.touches[0].screenX;
var y = event.touches[0].screenY;
Or if you want the position relative to the viewport, you can use clientX
and clientY
:
var x = event.touches[0].clientX;
var y = event.touches[0].clientY;
You can check the full list of properties and more info here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.