createjs 实现封装 drawImage

Fork Me On Github
zodream 游戏 TypeScript 2020年05月

问题

createjs 中,默认是没有封装 canvas 的 drawImage 方法,

想 添加图片到 canvas 上,只能使用

ts
   
const img: HTMLImageElement;
const box = new createjs.Shape();
box.graphics.beginBitmapFill(img).drawRect(0, 0, img.width, img.height);
123

如果想移动图片的位置,只能使用 box.xbox.y

而改变 drawRect 上的值,就是在图片上裁剪。默认 img 是无限重复的,

.drawRect(10, 10, img.width, img.height) 并不是移动到 10,10 再开始画整张图,而是先从 0,0 画,横向重复一次,纵向再重复一次,这是成 字排列四张图,然后 选取 10,10img.width + 10, img.height + 10 矩形区域显示

那么,想从 10,10 开始画整张图该怎么办?

解决方法

canvas 默认是有 drawImage 方法,调用就行了

ts
                   
class ImgFill {
    constructor(
        private img: HTMLImageElement,
        private x: number,
        private y: number,
        private width: number,
        private height: number
    ) {

    }

    public exec(ctx: CanvasRenderingContext2D) {
        ctx.save();
        ctx.drawImage(this.img, 0, 0, this.img.width, this.img.height, this.x, this.y, this.width, this.height);
        ctx.restore();
    }
}

box.graphics.append(new ImgFill(img, 10, 10, img.width, img.height));
12345678910111213141516171819

实现一个封装的对象,exec 方法是这个对象必须有的,有这个方法,才能被调用,实现绘制。

点击查看全文
标签: createjs
0 267 0
Tween._inited does not reset if scene is being destroyed or removed inside the game and rebuild