[英]HTML canvas - drawing disappear on resizing
我在 HTML canvas 元素中創建了一個基本形狀,效果很好。
當我調整畫布大小時出現問題,畫布中的所有繪圖都消失了。 這是正常行為嗎? 或者是否有可用於停止此功能的功能?
解決此問題的一種方法是在調整畫布大小時再次調用繪圖函數,但是如果要繪制大量內容,這可能不是很有效。
最好的方法是什么?
這是示例代碼的鏈接https://gist.github.com/2983915
調整大小時需要重新繪制場景。
設置畫布的寬度或高度,即使您將其設置為與之前相同的值,不僅會清除畫布,還會重置整個畫布上下文。 任何設置的屬性( fillStyle
、 lineWidth
、剪輯區域等)也將被重置。
如果您無法從表示畫布的任何數據結構中重繪場景,您始終可以通過將其繪制到內存畫布、設置原始寬度並繪制內部畫布來保存整個畫布本身。記憶畫布回到原來的畫布。
這是保存畫布位圖並在調整大小后將其放回原處的一個非常簡單的示例:
如果您關心性能,另一種方法是使用去抖動。 它不會調整大小或重新繪制您拖動的每個位置。 但它只會在調整大小時調整大小。
// Assume canvas is in scope
addEventListener.("resize", debouncedResize );
// debounce timeout handle
var debounceTimeoutHandle;
// The debounce time in ms (1/1000th second)
const DEBOUNCE_TIME = 100;
// Resize function
function debouncedResize () {
clearTimeout(debounceTimeoutHandle); // Clears any pending debounce events
// Schedule a canvas resize
debounceTimeoutHandle = setTimeout(resizeCanvas, DEBOUNCE_TIME);
}
// canvas resize function
function resizeCanvas () { ... resize and redraw ... }
我有同樣的問題。 試試下面的代碼
var wrapper = document.getElementById("signature-pad");
var canvas = wrapper.querySelector("canvas");
var ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
它保持原樣
對我有用的一件事是使用requestAnimationFrame()
。
let height = window.innerHeight;
let width = window.innerWidth;
function handleWindowResize() {
height = window.innerHeight;
width = window.innerWidth;
}
function render() {
// Draw your fun shapes here
// ...
// Keep this on the bottom
requestAnimationFrame(render);
}
// Canvas being defined at the top of the file.
function init() {
ctx = canvas.getContext("2d");
render();
}
當我不得不調整畫布大小以將其調整到屏幕時,我遇到了同樣的問題。 但我用這段代碼解決了它:
var c = document.getElementById('canvas'); ctx = c.getContext('2d'); ctx.fillRect(0,0,20,20); // Save canvas settings ctx.save(); // Save canvas context var dataURL = c.toDataURL('image/jpeg'); // Resize canvas c.width = 50; c.height = 50; // Restore canvas context var img = document.createElement('img'); img.src = dataURL; img.onload=function(){ ctx.drawImage(img,20,20); } // Restote canvas settings ctx.restore();
<canvas id=canvas width=40 height=40></canvas>
我也遇到了這個問題。但是經過實驗,我發現調整畫布元素的大小會自動清除畫布上的所有繪圖! 試試下面的代碼
<canvas id = 'canvas'></canvas>
<script>
var canvas1 = document.getElementById('canvas')
console.log('canvas size',canvas1.width, canvas1.height)
var ctx = canvas1.getContext('2d')
ctx.font = 'Bold 48px Arial'
var f = ctx.font
canvas1.width = 480
var f1 = ctx.font
alert(f === f1) //false
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.