html5 2d小游戏,GitHub - pepsin/cax: HTML5 Canvas 2D Rendering Engine - 小程序、小游戏以及 Web 通用 Canvas 渲染引擎...-程序员宅基地

技术标签: html5 2d小游戏  

English | 简体中文

Cax 68747470733a2f2f696d672e736869656c64732e696f2f6e706d2f762f6361782e737667

HTML5 Canvas 2D Rendering Engine

Features

Simple API, Lightweight and High performance

Support PC and Mobile Canvas 2D Rendering and Mouse and Touch Event

Support event of element and element management like DOM

Turing complete group nesting system

Support clip and clip transformation

Built-in Text, Bitmap, Sprite, Graphics and Shape

Support SVG Path rendering

Built-in images loader

Built-in cross platform motion library → to2to

Demo

Wechart App Demo

xqbl.png

Docs

Getting Started

Get cax through npm or cdn:

npm i cax

Usage:

import cax from 'cax'

const stage = new cax.Stage(200, 200, 'body')

cax.loadImgs({

imgs: ['./wepay-diy.jpg'],

complete: (imgs) => {

const img = imgs[0]

const bitmap = new cax.Bitmap(img)

bitmap.x = stage.width / 2

bitmap.y = stage.height / 2

bitmap.rotation = -10

bitmap.originX = img.width / 2

bitmap.originY = img.height / 2

bitmap.filter('blur(10px)')

stage.add(bitmap)

stage.update()

}

})

You will see the following effect:

getting-start.png

Built-in Object

Group

For grouping, group can also nested group, and the parent container's properties will be superimposed on child properties, such as:

the x of group is 100, the x of bitmap in group is 200, and the x of the bitmap rendered to stage is 300.

the alpha of group is 0.7, the alpha of bitmap in group is 0.6, and the alpha of the bitmap rendered to stage is 0.42.

const group = new cax.Group()

const rect = new cax.Rect(100, 100 {

fillStyle: 'black'

})

group.add(rect)

stage.add(group)

stage.update()

Group has commonly used add and remove methods to add and delete elements. The first add will be drawn first, and all subsequent add will be covered above the top add.

Group Method

add

add child to group

groupObj.add(child)

remove

remove child from group

groupObj.remove(child)

empty

remove all the children from group

groupObj.empty()

replace

replace child by another obj

groupObj.replace (current, pre)

Stage

Stage is the largest top container inherited from Group, so have all the methods and props of Group.

Stage Method

update

Any element can't be seen on the stage. You must execute the update method.

stage.update()

Any element property is modified. Please perform stage.update() to update the stage, or put it in the timer.

cax.tick(stage.update.bind(stage))

scaleEventPoint

When the height of the canvas and the pixels of the canvas are not one-to-one, the event triggering position is inaccurate, and you can use the scaleEventPoint method to make the event correct.

//The width of the canvas is half the canvas pixel

stage.scaleEventPoint(0.5, 0.5)

Stage Prop

disableMoveDetection

Disable event detection for mouse or touch mobile. Default value in the web is false. You can change it:

stage.disableMoveDetection = true

Bitmap

const bitmap = new cax.Bitmap(img)

stage.add(bitmap)

stage.update()

If you only transmit URL instead of the instance of the Image object, you need to do this:

const bitmap = new cax.Bitmap('./wepay.png', ()=>{

stage.update()

})

stage.add(bitmap)

bitmap-prop

rect

You can set the picture clipping display area, and other transform attributes:

bitmap.rect = [0, 0, 170, 140]

bitmap.x = 200

bitmap.rotation = 30

Sprite

The sequence frame animation component can combine any region of any picture into a series of animations.

const sprite = new cax.Sprite({

framerate: 7,

imgs: ['./mario-sheet.png'],

frames: [

// x, y, width, height, originX, originY ,imageIndex

[0, 0, 32, 32],

[32 * 1, 0, 32, 32],

[32 * 2, 0, 32, 32],

[32 * 3, 0, 32, 32],

[32 * 4, 0, 32, 32],

[32 * 5, 0, 32, 32],

[32 * 6, 0, 32, 32],

[32 * 7, 0, 32, 32],

[32 * 8, 0, 32, 32],

[32 * 9, 0, 32, 32],

[32 * 10, 0, 32, 32],

[32 * 11, 0, 32, 32],

[32 * 12, 0, 32, 32],

[32 * 13, 0, 32, 32],

[32 * 14, 0, 32, 32]

],

animations: {

walk: {

frames: [0, 1]

},

happy: {

frames: [5, 6, 7, 8, 9]

},

win: {

frames: [12]

}

},

playOnce: false,

currentAnimation: "walk",

animationEnd: function () {

}

});

Sprite Method

gotoAndPlay

Jump to the current animationName and start playing

spriteObj.gotoAndPlay(animationName)

gotoAndStop

Jump to the current animationName and stop

spriteObj.gotoAndStop(animationName)

gotoAndPlayOnce

Jump to the current animationName and start playing, then destroy yourself after animation. Often used in explosions

spriteObj.gotoAndPlayOnce(animationName)

Text

Text object

const text = new cax.Text('Hello World', {

font: '20px Arial',

color: '#ff7700',

baseline: 'top'

})

Method

getWidth

Get text width

textObj.getWidth()

Graphics

The drawing object is used to draw graphics with Canvas instructions in the basic way of linking.

const graphics = new cax.Graphics()

graphics

.beginPath()

.arc(0, 0, 10, 0, Math.PI * 2)

.closePath()

.fillStyle('#f4862c')

.fill()

.strokeStyle('black')

.stroke()

graphics.x = 100

graphics.y = 200

stage.add(graphics)

In particular, if you perform a graphics connection rendering operation in a loop, be sure to add the clear () method, or the path will be overloaded to your browser:

cax.setInterval(function(){

graphics

.clear()

.beginPath()

.arc(0, 0, 10, 0, Math.PI * 2)

.stroke()

}, 16)

Shape

Unlike Graphics, Shape usually has limited width height, so it can be buffered with off screen Canvas. The following are Shape.

Rect

const rect = new cax.Rect(200, 100, {

fillStyle: 'black'

})

Circle

const circle = new cax.Circle(10)

Ellipse

const ellipse = new cax.Ellipse(120, 20)

Element

Element is a combination of multiple elements, such as Bitmap, Group, Text, Shape and other mixed images.

Button

const button = new cax.Button({

width: 100,

height: 40,

text: "Click Me!"

})

Property

Transform

name

Describe

x

Horizontal offset

y

Vertical offset

scaleX

Horizontal scaling

scaleY

Vertical scaling

rotation

rotation

skewX

skewX

skewY

skewY

originX

Rotation base point X

originY

Rotation base point Y

Alpha

Name

Describe

alpha

The transparency of the element

Notice that the father and son have set up alpha to do multiplicative stacking.

compositeOperation

Name

Describe

compositeOperation

The superposition pattern drawn from the source image to the target image

Notice that if you don't have a definition of compositeOperation to look up, find the nearest compositeOperation's parent container as its own compositeOperation.

Cursor

Name

Describe

cursor

The shape of the mouse

Fixed

Name

Describe

fixed

Whether to fixed or not, the default is false, and set to true will not overlay the transform of ancestors.

Shadow

Name

Describe

shadow

shadow

Usage:

obj.shadow = {

color: '#42B035',

offsetX: -5,

offsetY: 5,

blur: 10

}

Method

destroy

Destroy self

obj.destroy()

Event

Name

Describe

click

Click time trigger on the element

mousedown

Triggers when the mouse button is pressed on the element

mousemove

Trigger when the mouse pointer moves to the element

mouseup

Trigger when the mouse button is released on the element

mouseover

Trigger when the mouse pointer moves to the element

mouseout

Trigger when the mouse pointer moves out of the element

tap

Leave the finger and leave immediately

touchstart

The start of finger touch action

touchmove

Move the finger after touch

touchend

End of finger touch action

drag

Drag and drop

Motion

Cax has built-in to capability to write motion effects in a continuous way.

const easing = cax.To.easing.elasticInOut

cax.To.get(bitmap)

.to({ y: 340, rotation: 240 }, 2000, easing)

.begin(() => {

console.log("Task one has began!")

})

.progress(() => {

console.log("Task one is progressing!")

})

.end(() => {

console.log("Task one has completed!")

})

.wait(500)

.to()

.rotation(0, 1400, easing)

.begin(() => {

console.log("Task two has began!")

})

.progress(() => {

console.log("Task two is progressing!")

})

.end(() => {

console.log("Task two has completed!")

})

.start();

to and to are parallel

to and wait are serial

The serial between to and to is serial with the next to and to

If you want circular motion, you can use the cycle method:

cax.To.get(bitmap)

.to()

.y(340, 2000, cax.easing.elasticInOut)

.to

.y(0, 2000, cax.easing.elasticInOut)

.cycle()

.start()

It's important to note that, unlike tween.js, Cax uses the camelcase. For example, Cubic.In becomes cubicIn.

Clip

const stage = new cax.Stage(600, 400, 'body')

const bitmap = new cax.Bitmap('./wepay-diy.jpg', () => {

stage.update()

})

const clipPath = new cax.Graphics()

clipPath.arc(40, 40, 25, 0, Math.PI * 2)

bitmap.clip(clipPath)

stage.add(bitmap)

You can get the same effect with blow code:

const clipPath = new cax.Graphics()

clipPath.x = 40

clipPath.y = 40

clipPath.arc(0, 0, 25, 0, Math.PI * 2)

So you can find that clip graphics supports all the transformation props(x,y,scaleX,scaleY,rotation,skewX,skewY,originX,originY).

Custom Object

Custom Shape

Custom Shape inherits from cax.Shape:

class Sector extends cax.Shape {

constructor (r, from, to, option) {

super()

this.option = option || {}

this.r = r

this.from = from

this.to = to

}

draw () {

this.beginPath()

.moveTo(0, 0)

.arc(0, 0, this.r, this.from, this.to)

.closePath()

.fillStyle(this.option.fillStyle)

.fill()

.strokeStyle(this.option.strokeStyle)

.lineWidth(this.option.lineWidth)

.stroke()

}

}

Use the Shape:

const sector = new Sector(10, 0, Math.PI/6, {

fillStyle: 'red'

lineWidth: 2

})

stage.add(sector)

stage.update()

Custom Element

Custom Element inherits from cax.Group:

class Button extends cax.Group {

constructor (option) {

super()

this.width = option.width

this.roundedRect = new cax.RoundedRect(option.width, option.height, option.r)

this.text = new cax.Text(option.text, {

font: option.font,

color: option.color

})

this.text.x = option.width / 2 - this.text.getWidth() / 2 * this.text.scaleX

this.text.y = option.height / 2 - 10 + 5 * this.text.scaleY

this.add(this.roundedRect, this.text)

}

}

export default Button

Use the Button:

const button = new cax.Button({

width: 100,

height: 40,

text: "Click Me!"

})

In general, it is suggested that inherit Group from a slightly complex combination, which is conducive to expansion and management of internal components.

Who is using cax?

wx.pngqq.png

License

MIT

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_33897085/article/details/117747775

智能推荐

高通QSEE中使用qsee_stor_write_sectors函数存储数据到emmc的RPMB分区_高通rpmb-程序员宅基地

文章浏览阅读1.1k次。QSEE不会自动对你的数据进行加密的,除非使用SFS。存储在RPMB的数据是有权限写入的,不是任何人都可以写,写之前需要鉴权。如果需要防止数据泄露,那就需要在写RPMB之前对数据进行加密。介绍一下RPMB分区RPMB(Replay Protected Memory Block)Partition 是 eMMC 中的一个具有安全特性的分区。eMMC 在写入数据到 RPMB 时,会校验数据的合法性,只有指定的 Host 才能够写入,同时在读数据时,也提供了签名机制,保证 Host 读取到的数据是 RP_高通rpmb

绘制决策曲线decision curve analysis(DCA)_dca曲线-程序员宅基地

文章浏览阅读2.4w次,点赞6次,收藏67次。Decision curve analysis-DCA 论文《Decision Curve Analysis: A Novel Method for Evaluating Prediction Models》y轴是计算出的收益x轴是取不同的概率Pt的值通过不断变换Pt阈值,计算对应的收益值横直线和点虚线分别为全手术or全不手术的时候对应的收益。如果绘制的DCA曲线高于这两条曲线..._dca曲线

ADB指令大全_adb命令大全详解-程序员宅基地

文章浏览阅读1.7w次,点赞10次,收藏108次。adb指令快捷键玩转adb命令,可以让我们电脑端操作手机变得游刃有余。 - **adb的断开与连接** ```java adb devices :显示已连接的设备 adb disconnect :端口号 :adb断开某设备 adb connect :端口号:adb连接某设备(通常针对offline设备) adb kill-server:杀死adb adb start-server:重启adb adb reboot:重启机器 adb..._adb命令大全详解

CSS3笔记-程序员宅基地

文章浏览阅读102次。CSS的颜色表达颜色宝典CSS背景图片的设置 overflow: scroll; /*设置滚动条*/ background-image: url("resources/background.png"), url("resources/background.png"); /*左边的背景图会去覆盖右边的背景图,背景图还会覆盖背景颜色*/ background-repeat: no-repeat; _css3笔记

CTC loss的几种解码方法:贪心搜索 (greedy search)、束搜索(Beam Search)、前缀束搜索(Prefix Beam Search)_ctc beam search-程序员宅基地

文章浏览阅读1.5w次,点赞28次,收藏99次。CTC loss的几种解码方法:贪心搜索 (greedy search)、束搜索(Beam Search)、前缀束搜索(Prefix Beam Search)前言:预测新的样本输入对应的输出字符串,这涉及到解码。按照最大似然准则,最优的解码结果为:然而,上式不存在已知的高效解法。下面介绍几种实用的近似破解码方法。1 贪心搜索 (greedy search)原理:虽然 p(l|x) 难..._ctc beam search

systemVerilog测试频率_systemverilog频率检查-程序员宅基地

文章浏览阅读497次。initial begin real stime, duration; forever begin @(posedge clk_nic0) stime = $realtime; @(posedge clk_nic0) duration = $realtime - stime; clk_nic_freq+ 1000.0/duration; endend_systemverilog频率检查

随便推点

零碎蓝桥备战知识点-程序员宅基地

文章浏览阅读171次。最小生成树(Kruskal和Prim算法):http://blog.csdn.net/luoshixian099/article/details/51908175并查集:https://blog.csdn.net/niushuai666/article/details/6662911莫比乌斯反演:https://blog.csdn.net/ACdreamers/article/details...

CLIP还能做分割任务?哥廷根大学提出一个使用文本和图像prompt,能同时作三个分割任务的模型CLIPSeg,榨干CLIP能力...-程序员宅基地

文章浏览阅读2.8k次。点击上方“计算机视觉工坊”,选择“星标”干货第一时间送达作者丨小马来源丨我爱计算机视觉本篇分享 CVPR 2022 论文『Image Segmentation Using Text and Image Prompts』,哥廷根大学提出了一个使用文本和图像prompt,能同时作三个分割任务的模型CLIPSeg,榨干CLIP的能力!详细信息如下:论文地址:https://ar..._referring image segmentation clip

安装和更新node的正确姿势-程序员宅基地

文章浏览阅读6.9k次,点赞6次,收藏4次。干货时刻本文主要讲解了如何安装node,以及如何更新node的版本`。node.js 是什么简称node,是基于Chrome V8引擎的JavaScript(JS)运行时环境node 安装进入node 官网,点击如下图所示的安装包即可下载,不同系统用户可根据自己的系统选择相应的安装包下载,作者用windows演示下载好后,我们自定义一个文件夹作为安装目录,例如作者的就是E:\System_disk_app\Nodejs。双击下载好的node-v16.14.2-x64.msi文件,弹出安装向导_更新node

【Rails】inverse_of在has_many和belongs_to中的用法_rails inverse of-程序员宅基地

文章浏览阅读1.5k次。最近使用Rails时,遇到了通过关联关系来多次访问同一条record,虽然得到的内容一样,但是每次都会创建不同对象的情况。通过查询Rails官方文档,找到了对关联关系的一种设置inverse_of,可以避免在一些情况下重复创建对象的问题。但是,文档中提到了inverse_of的限制:不能和 :through 选项同时使用不能和 :polymorphic 选项同时使用不能和 :as 选项同时使用_rails inverse of

window.showModalDialog() 过时替代方案_window.showmodaldialog替代方法-程序员宅基地

文章浏览阅读8.2k次。一、window.showModalDialog 方法说明window.showModalDialog( ) 方法的作用是创建和展示一个指向特定网页的模态对话框。该方法已经过时,特性已经从 Web 标准中删除,虽然一些浏览器目前仍然支持它,但也许会在未来的某个时间停止支持,请尽量不要使用该特性。此方法已在Chrome 43和Firefox 56中删除,当前仅IE浏览器支持该特性。如果正在开发的功能,需要使用到JS的对话框,应该使用window.open( ) 方法。如果是对老项目进行维护,_window.showmodaldialog替代方法

pdsh 安装步骤_centos7 源码安装pdsh-程序员宅基地

文章浏览阅读3k次。 pdsh安装步骤Skip to end of metadataCreated and last modified by wenqi.kang on Oct 19, 2017Go to start of metadata0.安装环境centos6.5 & centos7.21.解压并安装安装包: pdsh-2.26.zipunzip pdsh-2.26.zip..._centos7 源码安装pdsh

推荐文章

热门文章

相关标签