简体   繁体   English

使用 Javascript 在 Mousedown 上使动画精灵跟随 cursor

[英]Make Animated Sprite follow cursor on Mousedown with Javascript

This is my first posted question, so be gentle lol.这是我第一个发布的问题,所以要温柔哈哈。 I am trying to make a little game that will display different animated sprites on a canvas element that is laid over a user's webcam feed.我正在尝试制作一个小游戏,该游戏将在 canvas 元素上显示不同的动画精灵,该元素位于用户的网络摄像头提要上。 Right now I am just working with one sprite to get the functionality right.现在我只是在使用一个精灵来获得正确的功能。 I only want the sprite to appear and follow the mouse when left-click is held down.我只希望精灵在按住左键时出现并跟随鼠标。 Right now the sprite appears on mousedown and animates, but disappears if I move the mouse instead of following.现在精灵出现在 mousedown 上并动画,但如果我移动鼠标而不是跟随它就会消失。 I only want it to disappear on mouseup.我只希望它在 mouseup 时消失。 I have looked all over for the answer, but haven't been able to find one.我已经到处寻找答案,但一直找不到。 Here is the js I have:这是我的js:

'use strict';

const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const errorMsgElement = document.querySelector('span#errorMsg');

canvas.width = window.innerWidth;
canvas.height =window.innerHeight;

const constraints = {
//  audio: true,
 video: {
    //  width: 1280, height: 720
        width: window.innerWidth,
        height: window.innerHeight
    }

};

// Access webcam
async function init() {
 try {
     const stream = await navigator.mediaDevices.getUserMedia(constraints);
     handleSuccess(stream);
 } catch (e) {
     errorMsgElement.innerHTML = `navigator.getUserMedia error:${e.toString()}`;
 }
}

// Success
function handleSuccess(stream) {
 window.stream = stream;
 video.srcObject = stream;
}

// Load init
init();

//Code for drawing sprite on Canvas
var image = new Image();
image.src = "Starsprite.png";

var ctx = canvas.getContext("2d");
let magic = false;

var spriteWidth = 187; 
var spriteHeight = 60; 

var rows = 1; 
var cols = 3; 

var width = spriteWidth/cols; 
var height = spriteHeight/rows; 

var curFrame = 0; 
var frameCount = 3; 

let x =0;
let y =0; 

var srcX=0; 
var srcY=0; 

function startPosition(e){
    magic =true;
    x =e.clientX;
    y =e.clientY;
   
}

function movePosition(e){
    
    ctx.clearRect(x,y,width,height);
    x =e.clientX;
    y =e.clientY;
}

function endPosition(){
    magic =false;
    ctx.clearRect(x,y,width,height);
}

canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mousemove",movePosition);
canvas.addEventListener("mouseup", endPosition);
canvas.addEventListener("mousedown",draw);


function updateFrame(){
    curFrame = ++curFrame % frameCount;                 
    srcX = curFrame * width;  
}


function draw(){
    if (!magic) return;
    ctx.clearRect(x,y,width,height);
    updateFrame();
    ctx.drawImage(image,srcX,srcY,width,height, x,y,width,height);
    console.log(x + ", " + y);
   
}


setInterval(draw,200);

The movePosition function does update the x & y coordinates, but the sprite doesn't show while the mouse is moving. movePosition function 确实更新了 x & y 坐标,但鼠标移动时精灵不显示。 I tried creating an event listener to run the draw function on mousemove, but it messes up the animation because it fires every time the browser updates the mouse position.我尝试创建一个事件侦听器以在 mousemove 上运行绘图 function,但它弄乱了 animation,因为它每次浏览器更新鼠标 position 时都会触发。 Any ideas on tackling this problem?关于解决这个问题的任何想法?

Ok, so I have worked some more on it and animated the movement instead of trying to call the function over again.好的,所以我在这方面做了更多工作,并为运动设置了动画,而不是再次尝试调用 function。 I based this on instructions for animating keystroke inputs.我基于动画按键输入的说明。 It works fairly well, but if I move the mouse very quickly to a new position it doesn't follow it all the way.它工作得相当好,但是如果我将鼠标快速移动到新的 position 上,它就不会一直跟随它。

//Code for drawing on Canvas
var image = new Image();
image.src = "Starsprite.png";

var ctx = canvas.getContext("2d");
let magic = false;

var spriteWidth = 187; 
var spriteHeight = 60; 

var rows = 1; 
var cols = 3; 

var width = spriteWidth/cols; 
var height = spriteHeight/rows; 

var curFrame = 0; 
var frameCount = 3; 

let x =0;
let y =0; 

let mousex =0;
let mousey =0;
var stillx =0;
var stilly =0;

var srcX=0; 
var srcY=0; 

var left =false;
var right =false;
var up = false;
var down = false;
var speed = 60;
var lift = 30;
var buffer = 100;


function startPosition(e){
    magic =true;
    x =e.clientX;
    y =e.clientY;
}

function moveDirection(e){
    
    stillx = x + buffer;
    stilly = y + buffer;
    mousex = e.clientX;
    mousey = e.clientY;

    if(mousex>stillx){
    left = false;
    right = true; 
    
}
    if(mousex<stillx){
    left = true;
    right = false; 
}
    if(mousey>stilly){
    down = true;
    up = false; 
}

    if(mousey<stilly){
        down = false;
        up = true; 
    }
    
}


function endPosition(){
    magic =false;
    ctx.clearRect(x,y,width,height);
}
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mousemove",moveDirection);
canvas.addEventListener("mouseup", endPosition);
canvas.addEventListener("mousedown",draw);

function moveSprite(){
    if(right && x<canvas.width-width){
        x+=speed; 
        // x+=speed;
        right =false;
    }
    if(left && x>0){
        x-=speed; 
        left=false;
    }
    if(down && y<canvas.height-height){
        y+=lift; 
        down=false;
    }
    if(up && y>0){
        y-=lift; 
        up=false;
    }
}

function updateFrame(){
    curFrame = ++curFrame % frameCount;                 
    srcX = curFrame * width; 
    moveSprite();
   
}


function draw(){
    if (!magic) return;
    ctx.clearRect(x,y,width,height);
    updateFrame();
    ctx.drawImage(image,srcX,srcY,width,height, x,y,width,height);
    
   
}

setInterval(draw,200);

If anyone has a better solution please let me know!如果有人有更好的解决方案,请告诉我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM