简体   繁体   English

根据图像动态设置画布的宽度和高度

[英]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, 您需要获取canvas元素,然后像这样更改其宽度和高度,

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/ 这是保存图像的链接, http://www.nihilogic.dk/labs/canvas2image/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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