【问题标题】:Change canvas width and height without losing the current draw在不丢失当前绘图的情况下更改画布宽度和高度
【发布时间】:2022-01-05 20:01:35
【问题描述】:

我正在创建一个像素艺术应用程序,当我想从画布中保存图像时,图像太小了,所以当我想调整它的大小时它似乎像素化了。

我想将其调整为更大的尺寸,但我不知道如何。

这是代码示例:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.beginPath();
ctx.rect(0, 0, 50, 50);
ctx.fillStyle = 'red'; 
ctx.fill();

document.write('<img style="width:300px;" src="'+c.toDataURL("image/png")+'"/>');

// This is an image with dimensions 108x108px and it seems very bad when i resize it to 300x300px
// I want to download the canvas image with more resolution
<canvas id="myCanvas" width="108" height="108" style="width: 300px; height:300px;">

</canvas>

【问题讨论】:

  • c 元素上设置widthheight 属性。

标签: javascript html css canvas


【解决方案1】:

您可以创建一个画布并将 imageData 放入其中。

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.beginPath();
ctx.rect(0, 0, 25, 25);
ctx.fillStyle = 'red';
ctx.fill();
ctx.beginPath();
ctx.rect(0, 25, 25, 25);
ctx.fillStyle = 'yellow';
ctx.fill();
ctx.beginPath();
ctx.rect(25, 0, 25, 25);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.beginPath();
ctx.rect(25, 25, 25, 25);
ctx.fillStyle = 'green';
ctx.fill();

var c2 = document.createElement("canvas");
c2.width = 50;
c2.height = 50;
var ctx2 = c2.getContext("2d");
var imageData = ctx.getImageData(0, 0, 50, 50);
ctx2.putImageData(imageData, 0, 0);

document.write('<img style="width:300px;" src="' + c2.toDataURL("image/png") + '"/>');

【讨论】:

    猜你喜欢
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多