TIL#155 console image 넣기

Dasom·2022년 3월 15일
0

css

목록 보기
6/6

console 창에 이미지 보이기

회사 프로젝트를 진행하면서 콘솔창에 회사 로고를 넣고 싶어서 구글링을 했었는데 여러 코드들을 넣어도 작동하지 않았다. 그래서 이번에 다시 시도를 하였는데 여전히 이미지는 받아오지 못했고 코드를 고친 끝에 드디어 성공했다!!

참고했던 코드는

(function(url) {
  // Create a new `Image` instance
  var image = new Image();

  image.onload = function() {
    // Inside here we already have the dimensions of the loaded image
    var style = [
      // Hacky way of forcing image's viewport using `font-size` and `line-height`
      'font-size: 1px;',
      'line-height: ' + this.height + 'px;',

      // Hacky way of forcing a middle/center anchor point for the image
      'padding: ' + this.height * .5 + 'px ' + this.width * .5 + 'px;',

      // Set image dimensions
      'background-size: ' + this.width + 'px ' + this.height + 'px;',

      // Set image URL
      'background: url('+ url +');'
     ].join(' ');

     // notice the space after %c
     console.log('%c ', style);
  };

  // Actually loads the image
  image.src = url;
})('https://i.cloudup.com/Zqeq2GhGjt-3000x3000.jpeg');

이거였는데 다른 스타일은 다 작동하는데 이미지만 받아오지 못했다.
경로가 잘못되었나 해서 확인해보아도 경로는 정확했다...

image에 제대로 적용된게 맞나 싶어 콘솔에 console.log(image)를 찍어보니
<img src='경로'> 정확하게 잘 나왔다.

또한 style 은 제대로 들어갔는지 console.log(style)을 찍어보아도 잘 나왔다. 스타일을 콘솔에 찍은 결과를 보다가
background: url(경로); 이 부분을 고쳐보자는 생각이 들어서 'background: url('+ url +');' 이부분의 코드를 url 이 아닌 image의 src로 바로 하게 되면 작동할 것 같아서 바꿔보았다.
거짓말처럼 잘 작동하였다!! 드디어 해결해서 기뻐서 쓰는 오늘의 블로그였다 😍

해결한 코드

<script>
export default {
	name: "App",
	created() {
		var image = new Image()

		image.onload = function () {
			let style = [
				"font-size: 1px;",
				"line-height: " + this.height + "px;",
				"padding: " + this.height * 0.5 + "px " + this.width * 0.5 + "px;",
				"background-size: " + this.width + "px " + this.height + "px;",
				"background-image: url(" + this.src + ");",
			].join(" ")
			console.log("%c ", style)
		}
		image.src = require("/src/assets/피카츄.png")
	},
}
</script>
profile
개발자꿈나무🌲

0개의 댓글