Skip to content

Instantly share code, notes, and snippets.

@xon52
Last active March 5, 2024 09:23
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xon52/fb895e33d64a8d322da165d158fa11b2 to your computer and use it in GitHub Desktop.
Save xon52/fb895e33d64a8d322da165d158fa11b2 to your computer and use it in GitHub Desktop.
Medium - Flexible Canvas Grid (without blurred lines)
<template>
<canvas class="gridCanvas"
:width="width"
:height="height"
></canvas>
</template>
<script>
export default {
name: 'xon-GridCanvas',
props: [ 'width', 'height' ],
methods: {
drawGrid () {
let ctx = this.$el.getContext('2d')
let s = 28
let nX = Math.floor(this.width / s) - 2
let nY = Math.floor(this.height / s) - 2
let pX = this.width - nX * s
let pY = this.height - nY * s
// Bonus code for choosing nX instead of s
/* let nX = 20
let s = Math.floor(this.width / (nX + 2))
let pX = this.width - nX * s
let nY = Math.floor((this.height - pX) / (this.width - pX) * nX)
let pY = this.height - nY * s */
let pL = Math.ceil(pX / 2) - 0.5
let pT = Math.ceil(pY / 2) - 0.5
let pR = this.width - nX * s - pL
let pB = this.height - nY * s - pT
ctx.strokeStyle = 'lightgrey'
ctx.beginPath()
for (var x = pL; x <= this.width - pR; x += s) {
ctx.moveTo(x, pT)
ctx.lineTo(x, this.height - pB)
}
for (var y = pT; y <= this.height - pB; y += s) {
ctx.moveTo(pL, y)
ctx.lineTo(this.width - pR, y)
}
ctx.stroke()
}
},
mounted () {
this.drawGrid()
}
}
</script>
<style scoped>
.gridCanvas {
position: relative !important;
border: lightgrey 1px solid;
border-radius: 5px;
box-shadow: 0 2px 3px rgba(0, 0, 0, 0.2);
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment