gpt4 book ai didi

javascript - 为什么更改 Canvas 大小后必须重新绘制图像?

转载 作者:行者123 更新时间:2023-11-27 23:23:12 27 4
gpt4 key购买 nike

我正在尝试创建一个小型模因生成器,允许用户使用他/她想要的任何 URL 并更改图像的大小。一切都按应有的方式工作,但我注意到,如果 Canvas 上已经有图像并且用户决定更改 Canvas 大小,则该图像将被“删除”。为什么会发生这种情况?有办法防止这种情况发生吗?

JS

window.onload = function(){
var canvas = document.getElementById("main");
var ctx = canvas.getContext("2d");
var open_image = document.getElementById("open_in_new_window");
var change_img_size = document.getElementById("change_img_size");
var get_canvas_width = canvas.getAttribute("width");
var get_canvas_height = canvas.getAttribute("height");
var image = new Image();

image.onload = function(){
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
console.log("Image drawn");
}

open_image.addEventListener("click", function(){
var user_img = document.getElementById("input_url").value;
image.src = user_img;
console.log(user_img);
})

change_img_size.addEventListener("click", function(){
var set_canvas_width = document.getElementById("change_img_width").value;
var set_canvas_height = document.getElementById("change_img_height").value;
console.log(set_canvas_width, set_canvas_height);
canvas.setAttribute("width", set_canvas_width);
canvas.setAttribute("height", set_canvas_height);
})
}

HTML

<canvas id="main" width="450" height="550"></canvas>
<div id="user_actions">
<input type="text" id="input_url" placeholder="Input image location." />
<input type="text" id="change_img_width" placeholder="Change image width." />
<input type="text" id="change_img_height" placeholder="Change image height." />
<button id="open_in_new_window">View Image</button>
<button id="change_img_size">Change Image Size</button>
</div>

这是一个Pen

最佳答案

spec的相关部分:

When the user agent is to set bitmap dimensions to width and height, it must run the following steps:

  1. Reset the rendering context to its default state.

  2. Clear the scratch bitmap's hit region list and its list of pending interface actions.

  3. Resize the scratch bitmap to the new width and height and clear it to fully transparent black.

  4. If the rendering context has an output bitmap, and the scratch bitmap is a different bitmap than the output bitmap, then resize the output bitmap to the new width and height and clear it to fully transparent black.

您可以尝试getImageData()在调整 Canvas 大小之前,然后 putImageData()之后,但我不确定同源策略是否允许。

如果你不需要改变 Canvas 的固有尺寸,你可以改变canvas.style.widthcanvas.style.height,这不会删除 Canvas 。

关于javascript - 为什么更改 Canvas 大小后必须重新绘制图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35208082/

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