0
在我的第一次畫布嘗試(一個經典的老虎機),表現是可怕的。在前幾次旋轉之後,Chrome幾乎崩潰。在此畫布示例中導致性能下降的原因是什麼?
它是使用原型嗎?
Stack希望我在這裏寫更多的文本提交,所以我會。
var Renderer = function(options) {
var self = this
_.extend(self, options)
self.positions = _.map(self.reels, function(r) { return 0 })
self.heights = _.map(self.reels, function(r) { return r.length * self.symbolHeight })
self.context = self.canvas.getContext('2d')
self.render()
}
Renderer.prototype.render = function() {
var self = this
self.context.drawImage(self.bg, 0, 0)
self.context.rect(0, 0, self.symbolWidth * self.rows, self.symbolHeight * self.reels.length)
self.context.clip()
for (var reel = 0; reel < self.reels.length; reel++) {
for (var row = 0; row <= self.rows; row++) {
var reelIndex = Math.floor(self.positions[reel]/self.symbolHeight) + row
, symbolOffset = self.positions[reel] % self.symbolHeight
if (reelIndex >= self.reels[reel].length) {
reelIndex -= self.reels[reel].length
}
var symbolIndex = self.reels[reel][reelIndex]
, x = reel * self.symbolWidth
, y = row * self.symbolHeight - symbolOffset
/*
console.log('drawing symbol', symbolIndex, 'from', self.symbolDims[symbolIndex].x,
self.symbolDims[symbolIndex].y, 'to', x, y)
*/
self.context.drawImage(
self.symbols,
self.symbolDims[symbolIndex].x,
self.symbolDims[symbolIndex].y,
self.symbolDims[symbolIndex].width,
self.symbolDims[symbolIndex].height,
x,
y,
self.symbolWidth,
self.symbolHeight
)
}
}
}
Renderer.prototype.spinupTick = function() {
var allReelsAtMaxSpeed = true
, maxReelSpeed = 20
, self = this
, acc = 1
, reel
for (reel = 0; reel < this.reels.length; reel++) {
if (!self.reelsMoving[reel]) continue
if (self.speeds[reel] < maxReelSpeed) {
if (Math.random() < 0.5) {
self.speeds[reel] += acc
}
allReelsAtMaxSpeed = false
}
self.positions[reel] -= self.speeds[reel]
if (self.positions[reel] < 0) {
self.positions[reel] += self.heights[reel]
}
}
if (allReelsAtMaxSpeed) {
var allReelsStopped = true
for (reel = 0; reel < self.reels.length; reel++) {
if (!self.reelsMoving[reel]) continue
var stopSpot = self.stops[reel] * self.symbolHeight
console.log('stop spot', stopSpot, 'position', self.positions[reel])
if (stopSpot - self.positions[reel] <= self.speeds[reel]) {
self.reelsMoving[reel] = false
self.positions[reel] = stopSpot
} else {
allReelsStopped = false
}
}
if (allReelsStopped) {
clearInterval(self.timer)
self.timer = null
}
}
self.render()
}
Renderer.prototype.spin = function() {
var self = this
self.speeds = _.map(self.reels, function() { return 0 })
self.reelsMoving = _.map(self.reels, function() { return true })
self.stops = [0, 1, 2]
self.timer = setInterval(_.bind(self.spinupTick, self), 1000/60)
}
http://jsfiddle.net/abrkn/yNtEE/7/
我很遺憾地告訴這並沒有崩潰,我的電腦中調用context.beginPath()。事實上小提琴似乎根本不起作用... –
誰知道?它不工作!只有一堆錯誤和403。 – adeneo
沒有分號碼? – Stuart