)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Faster than save/restore HTML5 canvas

  1. const canvas = document.createElement('canvas')
  2. const c = canvas.getContext('2d')
  3.  
  4. canvas.width = innerWidth
  5. canvas.height = innerHeight
  6.  
  7. document.body.append(canvas)
  8.  
  9. c.fillStyle = 'black'
  10. c.fillRect(0, 0, canvas.width, canvas.height)
  11.  
  12. class Shooter {
  13.   constructor() {
  14.     this.x = innerWidth / 2
  15.     this.y = innerHeight / 2
  16.     this.vx = Math.random() * 10 - 5
  17.     this.vy = Math.random() * 10 - 5
  18.     this.color = 'rgba(255, 0, 0, 0.5)'
  19.     this.size = 10
  20.     this.halfSize = this.size / 2
  21.   }
  22.   draw() {
  23.     this.x += this.vx
  24.     this.y += this.vy
  25.  
  26.     if (this.x < 0) {
  27.       this.x = innerWidth
  28.     } else if (this.x > innerWidth) {
  29.       this.x = 0
  30.     }
  31.  
  32.     if (this.y < 0) {
  33.       this.y = innerHeight
  34.     } else if (this.y > innerHeight) {
  35.       this.y = 0
  36.     }
  37.  
  38.     c.fillStyle = this.color
  39.     c.translate(this.x, this.y)
  40.     c.fillRect(-this.halfSize, -this.halfSize, this.size, this.size)
  41.  
  42.     c.setTransform(1, 0, 0, 1, 0, 0)
  43.   }
  44. }
  45.  
  46. const NUM = 1000
  47. const shooters = []
  48. for (let i = 0; i < NUM; i++) {
  49.   shooters.push(new Shooter())
  50. }
  51.  
  52. function loop() {
  53.   c.fillStyle = 'rgba(0, 0, 0, 0.1)'
  54.   c.fillRect(0, 0, innerWidth, innerHeight)
  55.  
  56.   for (let i = 0; i < NUM; i++) {
  57.     shooters[i].draw()
  58.   }
  59.   requestAnimationFrame(loop)
  60. }
  61. loop()

Using setTransform(1, 0, 0, 1, 0, 0) is faster than using save and restore. If you don’t need to save context info like fills, line styles etc… consider this method.

Simple Way to Validate CSS Colors

  1. function isColor(col) {
  2.   const cache = isColor[col]
  3.   if (cache != null) {
  4.     console.log('- reading cache')
  5.     return cache
  6.   }
  7.   isColor.el.style = ''
  8.   isColor.el.style.color = col
  9.   return isColor[col] = !!isColor.el.style.color
  10. }
  11. isColor.el = document.createElement('div')
  12.  
  13.  
  14. console.log('is "red" a color?', isColor('red'))
  15. console.log('from the cache: ', isColor('red'))
  16.  
  17. console.log('is "rgbx(1, 2, 3)" a color?', isColor('rgbx(1, 2, 3)'))
  18.  
  19. console.log('is "#0f0" a color?', isColor('#0f0'))
  20.  
  21. console.log('is "hsl(192, 50%, 50%)" a color?', isColor('hsl(192, 50%, 50%)'))
  22. console.log('from the cache: ', isColor('hsl(192, 50%, 50%)'))
  23.  
  24. console.log('is "lab(2000.1337% -8.6911 -159.131231 / .987189732)" ?',
  25.   isColor('lab(2000.1337% -8.6911 -159.131231 / .987189732)'))
  26.  
  27. console.log('is "snippetZone" ?', isColor('snippetZone'))

I find this technique is usually good enough to validate colors…

// color // css // dom // graphics // hacks // hex // html // javascript // tricks

Parametric Equation for Rectangle

  1. // from http://math.stackexchange.com/questions/69099/equation-of-a-rectangle
  2. const rect = (px, py, rx, ry, t) => ({
  3.   x: px + rx + rx * (Math.abs(Math.cos(t)) * Math.cos(t) + Math.abs(Math.sin(t)) * Math.sin(t)),
  4.   y: py + ry + ry * (Math.abs(Math.cos(t)) * Math.cos(t) - Math.abs(Math.sin(t)) * Math.sin(t))
  5. })
  6.  
  7. const SIZE = 200
  8.  
  9. const c = document.body.appendChild(
  10.   Object.assign(document.createElement`canvas`,
  11.     { width: SIZE, height: SIZE }
  12.   )).getContext`2d`
  13.  
  14. c.fillStyle = 'black'
  15. c.fillRect(0, 0, SIZE, SIZE)
  16.  
  17. let t = 0
  18. setInterval(() => {
  19.   const { x, y } = rect(20, 20, 60, 70, t)
  20.   c.fillStyle = 'rgba(255, 0, 0, .1)'
  21.   c.fillRect(x, y, 10, 10)
  22.   t += .05
  23. }, 16)

Wanted to know how to do this for something back in 2015. Great math stackexchange answer here: http://math.stackexchange.com/questions/69099/equation-of-a-rectangle

Could be optimized but leaving as is to match:

x = p(|cos t|cos t + |sin t| sin t)
y = p(|cos t|cos t - |sin t| sin t)

One small change here is to add the width and height to the offset so that it draws from the upper left hand corner instead of the center…

Divide Rectangle Into Smaller Rectangles

  1. const rand = num => ~~(Math.random() * num)
  2.  
  3. let rectNum = 2 + rand(10)
  4. let rectCount = 0
  5.  
  6. document.body.appendChild(document.createElement('div')).innerText =
  7.   'click anywhere to regenerate'
  8.  
  9. function reset() {
  10.   ;[...document.querySelectorAll('.rect')].forEach(rect => rect.remove())
  11.   rectNum = 2 + rand(10)
  12.   rectCount = 0
  13.   newRect(300, 300, 50, 50)
  14. }
  15. reset()
  16. onpointerup = reset
  17.  
  18. function newRect(w, h, xp, yp) {
  19.   const rect = document.body.appendChild(document.createElement('div'))
  20.  
  21.   rect.classList.add('rect')
  22.   rectCount++
  23.  
  24.   Object.assign(rect.style, {
  25.     position: 'absolute',
  26.     left: `${xp}px`,
  27.     top: `${yp}px`,
  28.     width: `${w}px`,
  29.     height: `${h}px`,
  30.     outline: `1px solid black`,
  31.   })
  32.  
  33.   const props = {
  34.     x: xp,
  35.     y: yp,
  36.     height: h,
  37.     width: w,
  38.     seed: rand(3),
  39.     divide() {
  40.       const div = 2 + rand(5 * Math.random() * Math.random())
  41.       if (rand(2) == rand(2)) {
  42.         const newHeight = this.height / div
  43.  
  44.         newRect(this.width, this.height - newHeight, this.x, this.y)
  45.         newRect(this.width, newHeight, this.x, this.y + this.height - newHeight)
  46.       } else {
  47.         const newWidth = w / div
  48.         newRect(this.width - newWidth, this.height, this.x, this.y)
  49.         newRect(newWidth, this.height, this.x + this.width - newWidth, this.y)
  50.       }
  51.       rect.remove()
  52.     },
  53.   }
  54.   window.requestAnimationFrame(() => {
  55.     if (rectCount < rectNum) {
  56.       props.divide()
  57.     } else {
  58.       console.log('DONE!')
  59.     }
  60.   })
  61. }

This snippet comes to mind from time to time – one easy way to divide a rectangle into smaller rectangles- I actually went back and looked it up as it was an answer to a student question from 2006. The original one was written in ActionScript 2. Have a look:

  1. var wormNum:Number = 123;
  2. var wormCount:Number = 0;
  3. newWorm(400, 400, 0, 0);
  4. this.onEnterFrame = function() {
  5. 	if (wormCount < wormNum) {
  6. 		for (var props:String in this) {
  7. 			if (this[props]._x != undefined) {
  8. 				this[props].divide();
  9. 			}
  10. 		}
  11. 	}
  12. };
  13. function newWorm(w, h, xp, yp) {
  14. 	var currWorm:MovieClip = this.createEmptyMovieClip("box"+wormCount, this.getNextHighestDepth());
  15. 	wormCount++;
  16. 	box(w, h, currWorm, random(0xFFFFFF));
  17. 	currWorm._x = xp;
  18. 	currWorm._y = yp;
  19. 	currWorm.seed = random(3);
  20. 	currWorm.divide = function() {
  21. 		var div = random(4)+(1+Math.random()*1);
  22. 		if (random(2) == random(2)) {
  23. 			// divide vertically
  24. 			var nh:Number = this._height/div;
  25. 			newWorm(this._width, this._height-nh, this._x, this._y);
  26. 			newWorm(this._width, nh, this._x, this._y+this._height-nh);
  27. 		} else {
  28. 			// divide horizonatlly
  29. 			var nw:Number = this._width/div;
  30. 			newWorm(this._width-nw, this._height, this._x, this._y);
  31. 			newWorm(nw, this._height, this._x+this._width-nw, this._y);
  32. 		}
  33. 		this.removeMovieClip();
  34. 	};
  35. }
  36. function box(w:Number, h:Number, mc:MovieClip, col:Number):Void {
  37. 	with (mc) {
  38. 		lineStyle(0, 0, 20);
  39. 		beginFill(col, 10);
  40. 		moveTo(0, 0);
  41. 		lineTo(w, 0);
  42. 		lineTo(w, h);
  43. 		lineTo(0, h);
  44. 		endFill();
  45. 	}
  46. }

Don’t remember why I called them worms instead of rectangles, some AS2 types floating around…

Little Grid

  1. const NUM = 9
  2. const col = 3
  3. const size = 30
  4. const pad = 10
  5. const box = (x, y) => Object.assign(
  6.   document.body.appendChild(
  7.     document.createElement('div')
  8.   ).style, {
  9.     position: 'absolute',
  10.     width: size + 'px', 
  11.     height: size + 'px',
  12.     top: y + 'px', 
  13.     left: x + 'px',
  14.     background: 'red'
  15. })
  16.  
  17. const off = (size + pad)
  18. for (let i = 0; i < NUM; i++) {
  19.   const x = (i % col) * off
  20.   const y = parseInt(i / col, 10) * off
  21.   box(x, y)
  22. }
snippet.zone ~ 2021-24 /// {s/z}