简体   繁体   中英

Setting canvas Width and Height according to that of image dynamically

I am working on a project where I have to listen for paste event and save the image from clipboard to server and display it on canvas for further drawing.

What is working: get clipboard image and save it, displaying the image on canvas as background.

What is not working: resizing canvas so that whole image can be displayed. Also, while saving, I does not save the drawing on background image rather it only saves the drawing.

I tried

 var newImg = document.getElementById('justimg');
    newImg.src = data.showthis;
    newImg.onload= function(){
        curHeight = newImg.height;
        curWidth = newImg.width;
        alert(curWidth);
        alert(curHeight);}

to get image attribute but its showing canvas attributes only.

 <img id="justimg">
<canvas id="bearimage" ></canvas>

Also please suggest how to save canvas drawing with background image.

You need to get the canvas element and then change its width and height like this,

var newImg = document.getElementById('justimg');
    newImg.src = data.showthis;
    newImg.onload= function(){
        var canvas = document.getElementById('bearimage');
        canvas.height = newImg.height ;
        canvas.width = newImg.width ;
        alert(canvas.height);
        alert(canvas.width);}

To save canvas image you first need to draw the image on it and then you can save it! Here is a link to save image, http://www.nihilogic.dk/labs/canvas2image/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM