BlurhashCanvas.vue 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <template>
  2. <canvas ref="canvas" :width="parseNumber(width)" :height="parseNumber(height)" />
  3. </template>
  4. <script type="text/javascript">
  5. import { decode } from 'blurhash';
  6. export default {
  7. props: {
  8. hash: {
  9. type: String,
  10. required: true
  11. },
  12. width: {
  13. type: [Number, String],
  14. default: 32
  15. },
  16. height: {
  17. type: [Number, String],
  18. default: 32
  19. },
  20. punch: {
  21. type: Number,
  22. default: 1
  23. }
  24. },
  25. mounted() {
  26. this.draw();
  27. },
  28. updated() {
  29. // this.draw();
  30. },
  31. beforeDestroy() {
  32. // this.hash = null;
  33. // this.$refs.canvas = null;
  34. },
  35. methods: {
  36. parseNumber(val) {
  37. return typeof val === 'number' ? val : parseInt(val, 10);
  38. },
  39. draw() {
  40. const width = this.parseNumber(this.width);
  41. const height = this.parseNumber(this.height);
  42. const punch = this.parseNumber(this.punch);
  43. const pixels = decode(this.hash, width, height, punch);
  44. const ctx = this.$refs.canvas.getContext('2d');
  45. const imageData = ctx.createImageData(width, height);
  46. imageData.data.set(pixels);
  47. ctx.putImageData(imageData, 0, 0);
  48. },
  49. }
  50. }
  51. </script>