Resize image proportionally to HTML5 size

I am trying to write a jQuery plugin that will have similar functionality for the Flash-based product editor on Zazzle.com. I need to know how, using the canvas context.drawImage() function, I can insert an image and resize it to fit the canvas without distorting it.

The image is 500x500px in size as well as the canvas, but for some reason, when I set 500x500 for the image size, this is the way to go.

Here is my complete code:

 (function( $ ) { jQuery.fn.productEditor = function( options ) { var defaults = { 'id' : 'productEditor', 'width' : '500px', 'height' : '500px', 'bgImage' : 'http://www.wattzup.com/projects/jQuery-product-editor/sampleProduct.jpg' }; return this.each(function() { var $this = $(this) var options = $.extend( defaults, options ); // Create canvas var canvas = document.createElement('canvas'); // Check if their browser supports the canvas element if(canvas.getContext) { // Canvas defaults var context = canvas.getContext('2d'); var bgImage = new Image(); bgImage.src = options.bgImage; bgImage.onload = function () { // Draw the image on the canvas context.drawImage(bgImage, 0, 0, options.width, options.height); } // Add the canvas to our element $this.append(canvas); // Set ID of canvas $(canvas).attr('id', options.id).css({ width: options.width, height: options.height }); } // If canvas is not supported show an image that says so else { alert('Canvas not supported!'); } }); }; })( jQuery ); 

Any other constructive criticism is also welcome.

+6
source share
1 answer

This is the problem:

$ (canvas) .attr ('id', options.id) .css ({width: options.width, height: options.height});

You set the width / height of the canvas CSS when you need to set the width and height attributes directly. You do not distort the drawn image, you distort the canvas itself. The canvas is still 300x150 (default) and just stretched to 500x500. Thus, right now you are drawing a 500x500 image on a stretched canvas 300x150!

You need to do:

  var defaults = { 'id' : 'productEditor', 'width' : '500', // NOT 500px, just 500 'height' : '500', // NOT 500px, just 500 'bgImage' : 'http://www.wattzup.com/projects/jQuery-product-editor/sampleProduct.jpg' }; ... // Create canvas var canvas = document.createElement('canvas'); canvas.width = options.width; canvas.height= options.height; ... $(canvas).attr('id', options.id); // DON'T change CSS width/height 

Note that changing the width or height of the canvas clears it, so this MUST be done before using drawImage.

+9
source

Source: https://habr.com/ru/post/899158/


All Articles