Resizing an image in an HTML5 canvas

后端 未结 18 2669
半阙折子戏
半阙折子戏 2020-11-22 03:37

I\'m trying to create a thumbnail image on the client side using javascript and a canvas element, but when I shrink the image down, it looks terrible. It looks as if it was

18条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 03:51

    I know this is an old thread but it might be useful for some people such as myself that months after are hitting this issue for the first time.

    Here is some code that resizes the image every time you reload the image. I am aware this is not optimal at all, but I provide it as a proof of concept.

    Also, sorry for using jQuery for simple selectors but I just feel too comfortable with the syntax.

    $(document).on('ready', createImage);
    $(window).on('resize', createImage);
    
    var createImage = function(){
      var canvas = document.getElementById('myCanvas');
      canvas.width = window.innerWidth || $(window).width();
      canvas.height = window.innerHeight || $(window).height();
      var ctx = canvas.getContext('2d');
      img = new Image();
      img.addEventListener('load', function () {
        ctx.drawImage(this, 0, 0, w, h);
      });
      img.src = 'http://www.ruinvalor.com/Telanor/images/original.jpg';
    };
    html, body{
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
      background: #000;
    }
    canvas{
      position: absolute;
      left: 0;
      top: 0;
      z-index: 0;
    }
    
    
      
        
        Canvas Resize
      
      
        
      
    

    My createImage function is called once when the document is loaded and after that it is called every time the window receives a resize event.

    I tested it in Chrome 6 and Firefox 3.6, both on the Mac. This "technique" eats processor as it if was ice cream in the summer, but it does the trick.

提交回复
热议问题