Search code examples
javascriptadobecreatejseaseljs

Drag object around a circle on mouse over - Adobe Animate/Create.js/Easel.js


Using Adobe Animate HTML5 Canvas which employs Create.js/Easel.js.

I have the following code which drags an object around a circle.

Works Ok, but the object should only be moveable when the cursor is over the object; object being streakRotatorKnob.

var knob_X = 454;
var knob_Y = 175;
var radius = 80;

root.streakRotatorKnob.addEventListener("pressmove",moveF.bind(this));

function moveF(e){ 
var rads = Math.atan2(stage.mouseY-knob_Y,stage.mouseX-knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
}

I have tried the following but it's not working at all with the if statement:

var knob_X = 454;
var knob_Y = 175;
var radius = 80;

root.streakRotatorKnob.addEventListener("pressmove",moveF.bind(this));

function moveF(e){
    if(stage.mouseY == root.streakRotatorKnob.y && stage.mouseX == root.streakRotatorKnob.x){
var rads = Math.atan2(stage.mouseY-knob_Y,stage.mouseX-knob_X);
e.currentTarget.x = knob_X + radius * Math.cos(rads);
e.currentTarget.y = knob_Y + radius * Math.sin(rads);
stage.update();
    }
}

UPDATE

Based on Muhammed Maruf's answer below (the Adobe Animate version), the following works better by removing the line:

root.c.addEventListener("rollout", rollout);

So we just have:

stage.enableMouseOver();
var knob_X = 454;
var knob_Y = 169;
var radius = 90;
var root = this;


root.c.addEventListener("rollover", rollover);
//root.c.addEventListener("rollout", rollout);

function rollover(e)
{
    console.log("rollover")
    root.c.addEventListener("pressmove", moveF);
}
function rollout(e)
{
    console.log("rollout")
    root.c.removeEventListener("pressmove", moveF);
}
function moveF(e)
{
    var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
    e.currentTarget.x = knob_X + radius * Math.cos(rads);
    e.currentTarget.y = knob_Y + radius * Math.sin(rads);
    stage.update();
}

Solution

  • This is how I edited the code. I think you meant that.

    stage.enableMouseOver();
    var knob_X = canvas.width/2;
    var knob_Y = canvas.height/2;
    var radius = 90;
    var root = this;
    root.streakRotatorKnob.addEventListener("rollover", rollover);
    root.streakRotatorKnob.addEventListener("rollout", rollout);
    function rollover(e)
    {
        console.log("rollover")
        root.streakRotatorKnob.addEventListener("pressmove", moveF);
    }
    function rollout(e)
    {
        console.log("rollout")
        root.streakRotatorKnob.removeEventListener("pressmove", moveF);
    }
    function moveF(e)
    {
        var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
        e.currentTarget.x = knob_X + radius * Math.cos(rads);
        e.currentTarget.y = knob_Y + radius * Math.sin(rads);
        stage.update();
    }
    

    (function (cjs, an) {
    
    var p; // shortcut to reference prototypes
    var lib={};var ss={};var img={};
    lib.ssMetadata = [];
    
    
    (lib.AnMovieClip = function(){
        this.actionFrames = [];
        this.ignorePause = false;
        this.gotoAndPlay = function(positionOrLabel){
            cjs.MovieClip.prototype.gotoAndPlay.call(this,positionOrLabel);
        }
        this.play = function(){
            cjs.MovieClip.prototype.play.call(this);
        }
        this.gotoAndStop = function(positionOrLabel){
            cjs.MovieClip.prototype.gotoAndStop.call(this,positionOrLabel);
        }
        this.stop = function(){
            cjs.MovieClip.prototype.stop.call(this);
        }
    }).prototype = p = new cjs.MovieClip();
    // symbols:
    // helper functions:
    
    function mc_symbol_clone() {
        var clone = this._cloneProps(new this.constructor(this.mode, this.startPosition, this.loop, this.reversed));
        clone.gotoAndStop(this.currentFrame);
        clone.paused = this.paused;
        clone.framerate = this.framerate;
        return clone;
    }
    
    function getMCSymbolPrototype(symbol, nominalBounds, frameBounds) {
        var prototype = cjs.extend(symbol, cjs.MovieClip);
        prototype.clone = mc_symbol_clone;
        prototype.nominalBounds = nominalBounds;
        prototype.frameBounds = frameBounds;
        return prototype;
        }
    
    
    (lib.Sembol1 = function(mode,startPosition,loop,reversed) {
    if (loop == null) { loop = true; }
    if (reversed == null) { reversed = false; }
        var props = new Object();
        props.mode = mode;
        props.startPosition = startPosition;
        props.labels = {};
        props.loop = loop;
        props.reversed = reversed;
        cjs.MovieClip.apply(this,[props]);
    
        // Katman_1
        this.shape = new cjs.Shape();
        this.shape.graphics.f("#000000").s().p("AhuBuQgtguAAhAQAAg/AtguQAvguA/AAQBBAAAtAuQAuAuAAA/QAABAguAuQgtAuhBAAQg/AAgvgug");
    
        this.timeline.addTween(cjs.Tween.get(this.shape).wait(1));
    
        this._renderFirstFrame();
    
    }).prototype = getMCSymbolPrototype(lib.Sembol1, new cjs.Rectangle(-15.6,-15.6,31.2,31.2), null);
    
    
    // stage content:
    (lib.index = function(mode,startPosition,loop,reversed) {
    if (loop == null) { loop = true; }
    if (reversed == null) { reversed = false; }
        var props = new Object();
        props.mode = mode;
        props.startPosition = startPosition;
        props.labels = {};
        props.loop = loop;
        props.reversed = reversed;
        cjs.MovieClip.apply(this,[props]);
    
        this.actionFrames = [0];
        this.isSingleFrame = false;
        // timeline functions:
        this.frame_0 = function() {
            if(this.isSingleFrame) {
                return;
            }
            if(this.totalFrames == 1) {
                this.isSingleFrame = true;
            }
            stage.enableMouseOver();
            
            var knob_X = canvas.width/2;
            var knob_Y = canvas.height/2;
            var radius = 90;
            var root = this;
            
            
            root.streakRotatorKnob.addEventListener("rollover", rollover);
            root.streakRotatorKnob.addEventListener("rollout", rollout);
            
            function rollover(e)
            {
                console.log("rollover")
                root.streakRotatorKnob.addEventListener("pressmove", moveF);
            }
            function rollout(e)
            {
                console.log("rollout")
                root.streakRotatorKnob.removeEventListener("pressmove", moveF);
            }
            
            function moveF(e)
            {
                var rads = Math.atan2(stage.mouseY - knob_Y, stage.mouseX - knob_X);
                e.currentTarget.x = knob_X + radius * Math.cos(rads);
                e.currentTarget.y = knob_Y + radius * Math.sin(rads);
                stage.update();
            }
        }
    
        // actions tween:
        this.timeline.addTween(cjs.Tween.get(this).call(this.frame_0).wait(1));
    
        // Katman_1
        this.streakRotatorKnob = new lib.Sembol1();
        this.streakRotatorKnob.name = "streakRotatorKnob";
        this.streakRotatorKnob.setTransform(207.8,131.8);
    
        this.timeline.addTween(cjs.Tween.get(this.streakRotatorKnob).wait(1));
    
        this._renderFirstFrame();
    
    }).prototype = p = new lib.AnMovieClip();
    p.nominalBounds = new cjs.Rectangle(467.2,316.2,-243.79999999999998,-168.79999999999998);
    // library properties:
    lib.properties = {
        id: '214D9CE6C84FD84795816AF703BF00E4',
        width: 550,
        height: 400,
        fps: 24,
        color: "#CCCCCC",
        opacity: 1.00,
        manifest: [],
        preloads: []
    };
    
    
    
    // bootstrap callback support:
    
    (lib.Stage = function(canvas) {
        createjs.Stage.call(this, canvas);
    }).prototype = p = new createjs.Stage();
    
    p.setAutoPlay = function(autoPlay) {
        this.tickEnabled = autoPlay;
    }
    p.play = function() { this.tickEnabled = true; this.getChildAt(0).gotoAndPlay(this.getTimelinePosition()) }
    p.stop = function(ms) { if(ms) this.seek(ms); this.tickEnabled = false; }
    p.seek = function(ms) { this.tickEnabled = true; this.getChildAt(0).gotoAndStop(lib.properties.fps * ms / 1000); }
    p.getDuration = function() { return this.getChildAt(0).totalFrames / lib.properties.fps * 1000; }
    
    p.getTimelinePosition = function() { return this.getChildAt(0).currentFrame / lib.properties.fps * 1000; }
    
    an.bootcompsLoaded = an.bootcompsLoaded || [];
    if(!an.bootstrapListeners) {
        an.bootstrapListeners=[];
    }
    
    an.bootstrapCallback=function(fnCallback) {
        an.bootstrapListeners.push(fnCallback);
        if(an.bootcompsLoaded.length > 0) {
            for(var i=0; i<an.bootcompsLoaded.length; ++i) {
                fnCallback(an.bootcompsLoaded[i]);
            }
        }
    };
    
    an.compositions = an.compositions || {};
    an.compositions['214D9CE6C84FD84795816AF703BF00E4'] = {
        getStage: function() { return exportRoot.stage; },
        getLibrary: function() { return lib; },
        getSpriteSheet: function() { return ss; },
        getImages: function() { return img; }
    };
    
    an.compositionLoaded = function(id) {
        an.bootcompsLoaded.push(id);
        for(var j=0; j<an.bootstrapListeners.length; j++) {
            an.bootstrapListeners[j](id);
        }
    }
    
    an.getComposition = function(id) {
        return an.compositions[id];
    }
    
    
    an.makeResponsive = function(isResp, respDim, isScale, scaleType, domContainers) {      
        var lastW, lastH, lastS=1;      
        window.addEventListener('resize', resizeCanvas);        
        resizeCanvas();     
        function resizeCanvas() {           
            var w = lib.properties.width, h = lib.properties.height;            
            var iw = window.innerWidth, ih=window.innerHeight;          
            var pRatio = window.devicePixelRatio || 1, xRatio=iw/w, yRatio=ih/h, sRatio=1;          
            if(isResp) {                
                if((respDim=='width'&&lastW==iw) || (respDim=='height'&&lastH==ih)) {                    
                    sRatio = lastS;                
                }               
                else if(!isScale) {                 
                    if(iw<w || ih<h)                        
                        sRatio = Math.min(xRatio, yRatio);              
                }               
                else if(scaleType==1) {                 
                    sRatio = Math.min(xRatio, yRatio);              
                }               
                else if(scaleType==2) {                 
                    sRatio = Math.max(xRatio, yRatio);              
                }           
            }
            domContainers[0].width = w * pRatio * sRatio;           
            domContainers[0].height = h * pRatio * sRatio;
            domContainers.forEach(function(container) {             
                container.style.width = w * sRatio + 'px';              
                container.style.height = h * sRatio + 'px';         
            });
            stage.scaleX = pRatio*sRatio;           
            stage.scaleY = pRatio*sRatio;
            lastW = iw; lastH = ih; lastS = sRatio;            
            stage.tickOnUpdate = false;            
            stage.update();            
            stage.tickOnUpdate = true;      
        }
    }
    an.handleSoundStreamOnTick = function(event) {
        if(!event.paused){
            var stageChild = stage.getChildAt(0);
            if(!stageChild.paused || stageChild.ignorePause){
                stageChild.syncStreamSounds();
            }
        }
    }
    an.handleFilterCache = function(event) {
        if(!event.paused){
            var target = event.target;
            if(target){
                if(target.filterCacheList){
                    for(var index = 0; index < target.filterCacheList.length ; index++){
                        var cacheInst = target.filterCacheList[index];
                        if((cacheInst.startFrame <= target.currentFrame) && (target.currentFrame <= cacheInst.endFrame)){
                            cacheInst.instance.cache(cacheInst.x, cacheInst.y, cacheInst.w, cacheInst.h);
                        }
                    }
                }
            }
        }
    }
    
    
    })(createjs = createjs||{}, AdobeAn = AdobeAn||{});
    var createjs, AdobeAn;
    <!DOCTYPE html>
    <!--
        NOTES:
        1. All tokens are represented by '$' sign in the template.
        2. You can write your code only wherever mentioned.
        3. All occurrences of existing tokens will be replaced by their appropriate values.
        4. Blank lines will be removed automatically.
        5. Remove unnecessary comments before creating your template.
    -->
    <html>
    <head>
    <meta charset="UTF-8">
    <meta name="authoring-tool" content="Adobe_Animate_CC">
    <title>index</title>
    <!-- write your code here -->
    <script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
    <script src="index.js"></script>
    <script>
    var canvas, stage, exportRoot, anim_container, dom_overlay_container, fnStartAnimation;
    function init() {
        canvas = document.getElementById("canvas");
        anim_container = document.getElementById("animation_container");
        dom_overlay_container = document.getElementById("dom_overlay_container");
        var comp=AdobeAn.getComposition("214D9CE6C84FD84795816AF703BF00E4");
        var lib=comp.getLibrary();
        handleComplete({},comp);
    }
    function handleComplete(evt,comp) {
        //This function is always called, irrespective of the content. You can use the variable "stage" after it is created in token create_stage.
        var lib=comp.getLibrary();
        var ss=comp.getSpriteSheet();
        exportRoot = new lib.index();
        stage = new lib.Stage(canvas);  
        //Registers the "tick" event listener.
        fnStartAnimation = function() {
            stage.addChild(exportRoot);
            createjs.Ticker.framerate = lib.properties.fps;
            createjs.Ticker.addEventListener("tick", stage);
        }       
        //Code to support hidpi screens and responsive scaling.
        AdobeAn.makeResponsive(false,'both',false,1,[canvas,anim_container,dom_overlay_container]); 
        AdobeAn.compositionLoaded(lib.properties.id);
        fnStartAnimation();
    }
    </script>
    <!-- write your code here -->
    </head>
    <body onload="init();" style="margin:0px;">
        <div id="animation_container" style="background-color:rgba(204, 204, 204, 1.00); width:550px; height:400px">
            <canvas id="canvas" width="550" height="400" style="position: absolute; display: block; background-color:rgba(204, 204, 204, 1.00);"></canvas>
            <div id="dom_overlay_container" style="pointer-events:none; overflow:hidden; width:550px; height:400px; position: absolute; left: 0px; top: 0px; display: block;">
            </div>
        </div>
    </body>
    </html>