[Canvas] Monitor mouse click or touch events on the HTML canvas

When making h5 canvas, you need to pay attention to the fact that using canvas components on html webpages to interact on different platforms sometimes fails, and compatibility processing is required. That is because the events on the mobile browser are either mouse clicks or screen touch events.

On PC browsers, click events are used,

Need to monitor the mouse click event on the canvas, the code is as follows,

//...
canvas.addEventListener('mousedown',(event)=>{
    
    
	const {
    
     x, y } = event;
	onTouchStart(x,y)
});
canvas.addEventListener('mousemove',(event)=>{
    
    
	const {
    
     x, y } = event;
	onTouchMove(x,y);
});
canvas.addEventListener('mouseup',onTouchEnd);

On mobile phone (touchable device) browsers and applets, touch events are used.

Need to monitor the touch event on the canvas, the code is as follows

//...
canvas.addEventListener('touchstart',(event)=>{
    
    
	const {
    
     pageX:x, pageY:y } = event.touches[0];
	onTouchStart(x,y);
});
canvas.addEventListener('touchmove',(event)=>{
    
    
	const {
    
     pageX:x, pageY:y } = event.touches[0];
	onTouchMove(x,y);
});
canvas.addEventListener('touchend',onTouchEnd);

To do compatible processing, write all the above codes again, and call the public method, the additional code is as follows

//触摸开始
function onTouchStart(x,y){
    
    
//...
}
//触摸移动
function onTouchMove(x,y){
    
    
//...
}
//触摸结束
function onTouchEnd(){
    
    
//...
}

That 's it, not much to say .

Please add a picture description

Guess you like

Origin blog.csdn.net/zs1028/article/details/129710357