简体   繁体   中英

Bitmap in Easeljs does not work with event listeners?

I'm trying to create a draggable background image in my canvas. Currently I have something like this:

var stage = new createjs.Stage("canvas");
createjs.Ticker.addEventListener("tick", tick);

var dragContainer = new createjs.Container();
stage.addChild(dragContainer);

dragContainer.on("pressmove", function (event) {
    event.currentTarget.x = event.stageX;
    event.currentTarget.y = event.stageY;
    stage.update();
});

// Add a thing
var shape = new createjs.Shape();
shape.graphics.beginFill("#000");
shape.graphics.drawRect(0, 0, 50, 50);

dragContainer.addChild(shape);

// Update the stage
function tick(event) {
    stage.update();
}

This works perfectly fine, everything is draggable, etc. The problem is, when I replace the shape drawn with graphics with a bitmap (which is the functionality I want), it doesn't work.

    //Add a thing, this doesn't work
    var shape = new createjs.Bitmap("http://www.graphic-design-employment.com/images/create-a-simple-shape.jpg")
    dragContainer.addChild(shape);

Here's a jsfiddle: http://jsfiddle.net/frozensoviet/5heLu2L1/ . Any ideas what I'm doing wrong?

You are likely seeing cross-origin errors. Your console should be showing you the error. This happens because EaselJS must access the stage pixels to determine when the content is intersected by the mouse.

I modified your fiddle to load an image from a server that supports CORS. There is an htaccess file in the folder, which has the line:

Header set Access-Control-Allow-Origin "*"

Then, it is just a matter of flagging the content as crossOrigin. Note that the crossOrigin flag must be set BEFORE you load the source.

var img = new Image();
img.crossOrigin = "Anonymous";
img.src = "http://playpen.createjs.com/CORS/duck.png";
var shape = new createjs.Bitmap(img);

EaselJS doesn't have built-in support for CORS, so you have to specify it on your images before you load and pass them in. PreloadJS does have CORS support.

If you can't support CORS on the server, there is another workaround. Specify a hitArea on the image that is the same size, and it will draw that instead of the image when doing hit-detection. Here is an updated Fiddle: http://jsfiddle.net/lannymcnie/5heLu2L1/2/

var shape = new createjs.Bitmap("http://playpen.createjs.com/CORS/duck.png");
shape.image.onload = function() {
    var hitArea = new createjs.Shape();
    hitArea.graphics.f("#000").dr(0,0,shape.image.width,shape.image.height);
    shape.hitArea = hitArea;
}

Hope that helps!

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.

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