Image resize canvas

后端 未结 2 1371
猫巷女王i
猫巷女王i 2021-01-27 20:30

I\'m trying to upload images and have them fit into different sized boxes....To give you an idea of what the application does: People upload images and have them printed onto po

2条回答
  •  伪装坚强ぢ
    2021-01-27 20:40

    I would like to suggest you use the easyCanvas library to do this. The reason for this is that the built-in drawImage method of context do not scale the image proportionally for you, and it involves a small dose of math to get it right, especially in cases where destination shape differs from original and you want it to cover the whole area.

    I made a method in this library to handle situations such as these allowing you to draw the original image proportionally into any shape even if the shape doesn't correspond with the original.

    See this demo for an live example.

    In essence what you do is to draw your uploaded image into the canvas with this method:

    ez.drawImageProp(image, x, y, width, height);
    

    where width and height would be that of destination.

    It also has offset parameters so you can move the image around within that shape where an offset of 0.5 is center, 0 is from left and 1 is from right:

    ez.drawImageProp(image, x, y, width, height, offsetX, offsetY);
    

    Assuming image is already available all you need to do is:

    var ez = new easyCanvas('canvas'); /// provide ID of existing canvas
    ez.drawImageProp(image, 0, 0, ez.width, ez.height);
    

    Disclaimer: I am the author of easyCanvas. easyCanvas is open-source (GPL3.0 license).

提交回复
热议问题