gpt4 book ai didi

javascript - 将 Canvas 转换为 PNG 返回空白图像

转载 作者:行者123 更新时间:2023-11-30 20:24:54 24 4
gpt4 key购买 nike

我在将 Canvas 转换为 PNG 时遇到问题。虽然 Canvas 看起来和我想要的一模一样,而且从 Canvas 到数据 URL PNG 的转换看起来是正确的,但图像是空白的。我还尝试将 div 转换为 PNG,但它对我不起作用,因为我想应用灰度滤镜。有人有什么想法吗?


JavaScript

var imgis = new Image();
var bubble = new Image();
var canvasWidth;
var canvasHeight;
var ctx = canvas.getContext('2d');
bubble.onload = function() {
var imgis = new Image();
var bubble = new Image();
var ctx = canvas.getContext('2d');
bubble.onload = function() {
// set the canvas' size
canvas.width = this.width;
canvas.height = this.height;
// first fill a rect
ctx.fillStyle = 'rgba(255, 255, 255, 0)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// set the gCO
ctx.globalCompositeOperation = 'luminosity';
// if the browser doesn't support Blend Modes
console.log(ctx.globalCompositeOperation)
if (ctx.globalCompositeOperation !== 'luminosity')
fallback(this);
else {
// draw the image
ctx.drawImage(this, 0, 0);
ctx.drawImage(imgis, 30, 60);
// reset the gCO
ctx.globalCompositeOperation = 'source-over';
}
}
imgis.crossOrigin = "anonymous";
bubble.crossOrigin = "anonymous";
imgis.src = "image1 src";
bubble.src = "image2 src";
function fallback(img) {
// first remove our black rectangle
ctx.clearRect(0, 0, canvas.width, canvas.height);
//draw the image
ctx.drawImage(img, 0, 0);
ctx.drawImage(imgis, 30, 60);

// get the image data
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var d = imgData.data;
// loop through all pixels
// each pixel is decomposed in its 4 rgba values
for (var i = 0; i < d.length; i += 4) {
// get the medium of the 3 first values
var med = (d[i] + d[i + 1] + d[i + 2]) / 3;
// set it to each value
d[i] = d[i + 1] = d[i + 2] = med;
}
// redraw the new computed image
ctx.putImageData(imgData, 0, 0);
}

canvas = document.getElementById('canvas');
var image = Canvas2Image.convertToPNG(canvas);
console.log(image.src);
// document.getElementById('theDemo').src = image.src;
var image_data = $(image).attr('src');
console.log(image_data);
$("#theDemo").attr('src', image_data);

HTML

<canvas id='canvas' > </canvas>
<img src="" id="theDemo" />

最佳答案

我假设您使用的是 canvas2image。您应该将 var image = Canvas2Image.convertToPNG(canvas); 替换为 Canvas2Image.convertToPNG(canvas, width, height)。希望对您有所帮助!

编辑 由于问题出在实际 Canvas 到 base64 的转换上,您可以尝试使用 .toDataURL() 方法而不是使用该库。我的评论解释了如何在您的特定代码中对此进行测试。

关于javascript - 将 Canvas 转换为 PNG 返回空白图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51026092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com