简体   繁体   English

如何下载 HTML5 canvas 的背景图片?

[英]How do I download the background image of an HTML5 canvas?

I have a program that randomizes the r, g, and b values for 2 rgb colors and creates a linear gradient mixing the colors.我有一个程序可以随机化 2 RGB colors 的 r、g 和 b 值,并创建混合 colors 的线性梯度。 However, the only way I can create that linear gradient is by setting the background-image of my canvas to that gradient, meaning when I download the canvas, it is blank, because the background image isn't dowloaded.但是,我可以创建线性渐变的唯一方法是将 canvas 的背景图像设置为该渐变,这意味着当我下载 canvas 时,它是空白的,因为没有下载背景图像。

CSS CSS

.window {
  width: 500px;
  height: 500px;
  background-image: linear-gradient(to right, white, black);
}

HTML HTML

<canvas id = 'randomgradient_canvas' class = 'window'></canvas>

JavaScript JavaScript

let r1, g1 b1, r2, g2, b2;
function randomizeColors() {
  r1 = Math.random() * 255;
  g1 = Math.random() * 255;
  b1 = Math.random() * 255;
  r2 = Math.random() * 255;
  g2 = Math.random() * 255;
  b2 = Math.random() * 255;
  document.getElementById('randomgradient_canvas').style = `background-image:linear-gradient(to left, rgb(${r1}, ${g1}, ${b1}), rgb(${r2}, ${g2}, ${b2}))`;
}

And this all works perfectly for making the gradient, the only problem is I can't find anywhere how to download an element's background image.这一切都非常适合制作渐变,唯一的问题是我无法在任何地方找到如何下载元素的背景图像。

The background defined by CSS is not drawn onto the canvas buffer, thus you can't get the pixel data of it. CSS 定义的背景没有绘制到 canvas 缓冲区中,因此您无法获取它的像素数据。 However, you can draw a gradient to the canvas using ctx.createLinearGradient() and then get the pixel data using ctx.getImageData or something else.但是,您可以使用ctx.createLinearGradient()为 canvas 绘制渐变,然后使用ctx.getImageData或其他方法获取像素数据。

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

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