So I was under the impression that rendering designs on the HTML5 canvas would be quite fast. I’m using the following code and I would think it would take less than a second to render, but it takes about 2 minutes total.
Code:
<script>
var canvas = document.getElementById("canvas")
ctx = canvas.getContext('2d')
maxW = window.innerWidth
maxH = window.innerHeight
x = -1
numLeft = 15
//maxW = 300
//maxH = 300
canvas.setAttribute("width", maxW)
canvas.setAttribute("height", maxH)
ctx.fillStyle = "rgba(0,0,0,.5)"
for(var j = 0; j < maxH; j++){
for(var i = 0; i < maxW; i++){
if(numLeft < 0){
if(x == -1){
ctx.fillStyle = "rgba(127,127,127,.5)"
//numLeft += 12
numLeft += 5
}
else{
ctx.fillStyle = "rgba(0,0,0,.5)"
//numLeft += 24
numLeft += 15
}
x *= -1
}
ctx.fillRect(i,j,i+1,j+1)
numLeft--
}
//numLeft -= 5 this one's crazy :D
numLeft -= 3
}
It’s supposed to draw diagonal stripes in black and grey. But again, it’s taking forever to render and would crash most people’s browsers. Any hints as to how to speed this up?
Since comments can’t be accepted as answers as far as I know, I’m posting @pimvdb comment as an answer. The problem was the way
fillRect()was being called, it was being called as if the all the parameters were coordinates(x, y, x2, y2)when in fact the parameters were a combination of coordinates and dimension(x, y, w, h).I confirmed that this was a major performance problem in your code with with this jsFiddle.
As mentioned there are other performance improvements you can make like pre-rendering and using line gradients but this addresses the immediate performance problem. In my test on Chrome performance went from 6 seconds to less than one.
Have you tried the performance suggests on html5rocks.com?