This article completes such an example, letting the protagonist move with the mouse, the effect is as follows:
The update function is the same as the previous article, the code is as follows:
Then look at The initialization part of init is the same as the example in the previous article. The code is as follows:
Then Define mousedown, mousemove, mouseup respectively, corresponding to mouse pressing, moving and lifting respectively. rise. The codes are as follows:
First use the following code to obtain the coordinates. The following code is used in various browsers:
var mx,my; if(ev.layerX || ev.layerX==0){ mx = ev.layerX; my = ev.layerY; }else if(ev.offsetX || ev.offsetX==0){ mx = ev.offsetX; my = ev.offsetY; }
Then check whether the mouse coordinates are within the range of the picture, and obtain the coordinate offset if within the range.
mousedown is within the picture range, in Re-obtain the image coordinates in move, release it when lifting the function, and then register the function to canvas to complete this example/
The above is the content of Html5 Canvas preliminary study notes (15) - mouse events. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!