从源画布复制后,Canvas呈现错误

时间:2016-08-05 16:03:37

标签: javascript html5 canvas

我有两个画布和一个选择按钮。

选择按钮用于更改第二个画布中的比例。

第一个画布的内容在第二个画布中复制。

当我使用选择按钮增加比例时,第二个画布会调整大小并完美缩放,但是他的渲染很糟糕(矩形和文本都是模糊的)。

有什么问题?

此处为源代码(您可以尝试https://jsfiddle.net/0kqqnkmp/):

<canvas id="canvas"></canvas>
<canvas id="canvas_second"></canvas>

<br>Choose your scale : <select onchange="change_scale(this);" autocomplete="off">
                            <option>0.5</option>
                            <option selected>1</option>
                            <option>1.5</option>
                            <option>2</option>
                        </select>


<script type="text/javascript">

//The canvas :
c = document.getElementById("canvas");
c.style.border = "solid #000000 1px";

//The second canvas :
c_second = document.getElementById("canvas_second");
c_second.style.border = "solid #000000 1px";

//Define the original width and height canvas :
ORIGINAL_WIDTH_CANVAS = 300;
ORIGINAL_HEIGHT_CANVAS = 300;

c.width = ORIGINAL_WIDTH_CANVAS;
c.height = ORIGINAL_HEIGHT_CANVAS;

c_second.width = ORIGINAL_WIDTH_CANVAS;
c_second.height = ORIGINAL_HEIGHT_CANVAS;

//The canvas context :
ctx = c.getContext("2d");
ctx_second = c_second.getContext("2d");

//Default scaling
scale = 1;

//Drawing function :
function draw()
{
    //Clear the drawing :
    ctx.clearRect(0, 0, ORIGINAL_WIDTH_CANVAS, ORIGINAL_HEIGHT_CANVAS);

    //Drawing a red rectangle :
    ctx.fillStyle = "#000000";
    ctx.fillRect(5, 5, 50, 50);

    //Drawing a text :
    ctx.font = "normal bold 20px sans-serif";
    ctx.fillText("Hello world", ORIGINAL_WIDTH_CANVAS-220, ORIGINAL_HEIGHT_CANVAS-10);


    //Clear the drawing on the second canvas :
    ctx_second.clearRect(0, 0, ORIGINAL_WIDTH_CANVAS, ORIGINAL_HEIGHT_CANVAS);

    //Copy drawing on the second canvas :
    ctx_second.drawImage(c, 0, 0);

}

//Function for scaling the second canvas :
function change_scale(this_select)
{   
    //Retrieve the scale value :
    scale = parseFloat(this_select.value);

    //Resize the second canvas :
    c_second.width = ORIGINAL_WIDTH_CANVAS * scale;
    c_second.height = ORIGINAL_HEIGHT_CANVAS * scale;

    //Apply scaling on the second canvas :
    ctx_second.scale(scale, scale);
}


//Draw :
setInterval("draw()", 300);

</script>

1 个答案:

答案 0 :(得分:1)

缩放图片时,您会看到模糊的结果。

画布实际上是位图图像。当按比例放大时,位图图像会变得模糊。

所以当你扩展&amp;将你的bitmap-canvas#1绘制到#2画布上,你会得到一个模糊的结果。

修复是scale(2,2)画布#2,然后重新发出相同的命令,绘制你的矩形&amp;文本到第一个画布上。

好的一点是scale会在重绘时自动处理更改[x,y]坐标。因此,您使用与用于绘制画布#1的完全相同的[x,y]坐标。

// scale the second canvas
secondContext.scale(2,2);

//Drawing a red rectangle :
secondContext.fillStyle = "#000000";
secondContext.fillRect(5, 5, 50, 50);

//Drawing a text :
secondContext.font = "normal bold 20px sans-serif";
secondContext.fillText("Hello world", ORIGINAL_WIDTH_CANVAS-220, ORIGINAL_HEIGHT_CANVAS-10);