简体   繁体   English

使用Javascript将画布转换为图像

[英]Transform a canvas into an image - with Javascript

First, I'd like to say that I have been looking for the answer for hours... 首先,我想说我一直在寻找答案几个小时...

The problem is the following. 问题如下。 I have a canvas in my HTML code which displays at the screen some drawings. 我的HTML代码中有一个画布,该画布在屏幕上显示了一些绘图。 What I want to do is to transform what I can see on my screen (in the canvas) into an image, which would be displayed in a "img" tag like classic images in websites. 我要做的是将屏幕(在画布上)看到的图像转换为图像,该图像将显示在“ img”标签中,就像网站上的经典图像一样。

In my HTML code, I have : 在我的HTML代码中,我有:

<canvas height="842" width="595"></canvas>

And when I look at the screen, I have indeed something. 当我看着屏幕时,我确实有东西。

But what I want in my code is something like that: 但是我想要的代码是这样的:

<img src="blabla" style="height: 842px; width: 595px";></img>

And the line above would be supposed to display an image which is identical to what we can see in the canvas. 并且上面的行应该显示的图像与我们在画布中看到的图像相同。

Here is a part of my javaScript code. 这是我的JavaScript代码的一部分。 The canvas variable is something that has been already created before and this is what displays what is in my canvas, so it works. canvas变量是已经创建的东西,它可以显示画布中的内容,因此可以正常工作。

var image = new Image();
image.src = canvas.toDataURL("image/jpg");

image.style.height = canvas.height;
image.style.width = canvas.width;

document.body.appendChild(image);

When I run my code and when I open DevTools, in my HTML code, there is the line, with an URL in the src tag. 当我运行代码并打开DevTools时,在HTML代码中,该行在src标记中带有URL。 But visually, on my screen, there is nothing. 但是从视觉上看,在我的屏幕上什么也没有。 The image is not even white, there is absolutely nothing. 图像甚至不是白色,绝对没有。 In DevTools, when I hover the line of the image, I can see that there is a place reserved to my image with the good dimensions, but there is nothing inside. 在DevTools中,当我将鼠标悬停在图像的线条上时,可以看到有一个保留给我的图像的位置,它的尺寸很好,但是里面什么也没有。 The console doesn't detect any error. 控制台未检测到任何错误。

What should I do ? 我该怎么办 ?

I've copy/paste you code and it works like a charm. 我已经复制/粘贴了您的代码,它的工作原理就像是一种魅力。 http://jsbin.com/hojuco/edit?html,css,js,output http://jsbin.com/hojuco/edit?html,css,js,输出

Do you draw something in you canvas before export it ? 在导出画布之前,您是否在画布中画了东西? Canvas are transparent on start so be sure it's not just empty. 画布在开始时是透明的,因此请确保它不仅仅是空的。

Otherwise, you mixed up your variable. 否则,您将变量混在一起。

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

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